How to pass an implemented virtual member function as a parameter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> class virtualClass{ public: virtual int a() = 0; }; class UnknownImplementation : public virtualClass{ public: int a() override { return 1;} }; class myFramework { public: int c(int (virtualClass::*implementedFunc)(void)){ implementedFunc(); return 2; } }; int main(){ //some user implements the virtual class and calls myFramework function myFramework* mfp = new myFramework(); std::cout << mfp->c(&(UnknownImplementation::a)) << std::endl; } |
您好,我正在开发一个框架,该框架应该调用一个已实现的虚拟函数并使用它。它类似于上面的代码。我得到的编译错误是:
testVirtual.cpp: In member function ‘int myFramework::c(int (virtualClass::)())’: testVirtual.cpp:16:19: error: must use ‘.’ or
‘->’ to call pointer-to-member function in ‘implementedFunc (...)’,
e.g. ‘(... -> implementedFunc) (...)’ implementedFunc();
^ testVirtual.cpp: In function ‘int main()’: testVirtual.cpp:24:47: error: invalid use of non-static member
function ‘virtual int UnknownImplementation::a()’ std::cout << mfp->c(&(UnknownImplementation::a)) << std::endl;号
如何解决这些问题?事先谢谢!
传递已实现类的实例并调用函数。
建立在sameerkn的评论,这个代码应该是:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 #include <iostream>
class virtualClass{
public:
virtual int a() = 0;
};
class mySubclass : public virtualClass{
public:
int a() override { return 1;}
};
int main(){
mySubclass * x= new mySubclass ();
// ...
std::cout << x->a () << std::endl;
}点这里是你的护照(或CAN对象类型
virtualClass 分)甲,即使他们可能是mySubclass 对象在现实生活和工作在静风a() 正确执行。myFramework 是完全不必要的。这就是
virtual methods for ofvirtualClass 是消费者不需要知道任何事类,可能现在或未来的衍生从它,如果我读正确的问题,这是你想要的。