您的位置:首页 > 其它

子类之间的成员函数互相调用

2017-03-12 16:31 176 查看
#include<iostream>
using namespace std;
//#pragma warning(disable:2162)
class A{
};
//定义成员函数类型
typedef void (A::*F)();
//强制类型转换
#define Class_Func_Cast(selector) (F)(&selector)

//#define str(selector) ##Class_Func_Cast(selector)##
//#define str(a) #a
//一定要共有继承,否则无法转换
class B:public A{
public:
void f(){
cout << "B::f" << endl;
}
//测试this和成员函数的调用
void test(){
F f = Class_Func_Cast(B::f);
(this->*f)();
cout << "B::test over" << endl;
}
//调用继承A的所有子类成员方法:void function();
static void callSonOfAClassVoidFunc(F f){
cout << "callSonOfAClassVoidFunc begin..." << endl;
A a;
(a.*f)();
cout << "callSonOfAClassVoidFunc end!" << endl;
}

};

class C:public A{
public:
void f1(){
cout << "C::f" << endl;
}
void f2(){
cout << "C::f2" << endl;
}
void f3(){
cout << "C::f3" << endl;
}
//在B类(其他类)中调用C类(自己的类)本身的成员函数
void testf123(){
B::callSonOfAClassVoidFunc(Class_Func_Cast(C::f1));
B::callSonOfAClassVoidFunc(Class_Func_Cast(C::f2));
B::callSonOfAClassVoidFunc(Class_Func_Cast(C::f3));
cout << "C::test123 end!" << endl;
}
};

int main(){
//cout << str(B::f) << endl;
cout << sizeof(F) << endl;
B b;
void (B::*f)() = &B::f;
(b.*f)();
F f1 = Class_Func_Cast(B::f);
(b.*f1)();
A a;
(a.*f1)();
b.test();
//f1();

auto f2 = Class_Func_Cast(B::f);
(a.*f2)();

C c;
c.testf123();

cout << "func wrapper over" << endl;

return 0;
}

4
B::f
B::f
B::f
B::f
B::test over
B::f
callSonOfAClassVoidFunc begin...
C::f
callSonOfAClassVoidFunc end!
callSonOfAClassVoidFunc begin...
C::f2
callSonOfAClassVoidFunc end!
callSonOfAClassVoidFunc begin...
C::f3
callSonOfAClassVoidFunc end!
C::test123 end!
func wrapper over

参考:


编译器错误 C2064

Visual Studio 2010

其他版本



项不会计算为接受“number”个参数的函数

通过表达式调用了函数。 该表达式未计算为函数指针。

下面的示例生成 C2064:

// C2064.cpp
int i, j;
char* p;
void func() {
j = i();    // C2064, i is not a function
p();        // C2064, p doesn't point to a function
}


下面的示例生成 C2064:

// C2064b.cpp
struct C {
void func1(){}
void func2(){}
};

typedef void (C::*pFunc)();

int main() {
C c;
pFunc funcArray[2] = {&C::func1, &C::func2};
(funcArray[0])();    // C2064
}


可能的解决方法:

// C2064c.cpp
struct C {
void func1(){}
void func2(){}
};

typedef void (C::*pFunc)();

int main() {
C c;
pFunc funcArray[2] = {&C::func1, &C::func2};
(c.* funcArray[0])();
}


下面的示例生成 C2064:

// C2064d.cpp
struct C {
typedef void (C::*pFunc)();
pFunc funcArray[2];
void func1(){}
void func2(){}
C() {
funcArray[0] = C::func1;
funcArray[1] = C::func2;
}
void func3() {
(funcArray[0])();   // C2064
}
};


可能的解决方案:

// C2064e.cpp
// compile with: /c
struct C {
typedef void (C::*pFunc)();
pFunc funcArray[2];
void func1(){}
void func2(){}
C() {
funcArray[0] = &C::func1;
funcArray[1] = &C::func2;
}
void func3() {
(this->* funcArray[0])();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐