您的位置:首页 > 编程语言 > C语言/C++

C++ member function pointer

2015-05-07 16:37 351 查看
//1.derived class can call the base class function, but the base class can not call the derived class function, member pointer can not do it

//2.c++ member function is strict

//3.the size of C++ pointer maybe not equal to the size of machine word

#include <stdio.h>

#include <iostream>
using namespace std;

//1.0--------------------------------------------------------------------------------------
//1.derived class can call the base class function, but the base class can not call the derived class function, member pointer can not do it

//2.c++ member function is  strict
class base
{
int a;
public:
void hello()
{
cout<<"base hello\n";
}

void world()
{
cout<<"base world\n";
}
};

class Derived1: public base
{
public:
void hello()
{
cout<<"Derived1 hello\n";
}

void call(Derived1 *b1, void (Derived1::*fun)())
{
(b1->*fun)();
}

};

class Derived2:public base
{
public:
void world()
{
cout<<"Derived2 world\n";
}
};

/*
void call(base *b1, void (base::*fun)()) //can not work
{
(b1->*fun)();
}
*/

void call(Derived1 *b1, void (Derived1::*fun)())
{
(b1->*fun)();
}

typedef void (Derived1::*pFun)();
//1.1--------------------------------------------------------------------------------------

class BaseClass {
public:
void BaseClassFun(int x, char *p) {
printf("In BaseClass\n"); };
};

class DerivedClass : public BaseClass {
public:
};

//1.1--------------------------------------------------------------------------------------

class CBase1 {};
class CBase2 {};
class CDerive2 : public CBase1, public CBase2 {};
typedef void (CDerive2::*FPderive2)();

int main() {
// Declare a member function pointer for BaseClass

typedef void (BaseClass::*m_f_p)(int, char *);
m_f_p memfunc_ptr;
memfunc_ptr = &DerivedClass::BaseClassFun;

DerivedClass *dc;
char pstr[]="";
( dc->*memfunc_ptr)(1,pstr);
//--------------------------------------------------------
//3.the size of C++ pointer maybe not equal to the size of machine word
void (*pf)();
cout << "sizeDerive2 = " << sizeof(pf) << endl;
size_t sizeDerive2 = sizeof(FPderive2);
cout << "sizeDerive2 = " << sizeDerive2 << endl;
//---------------------------------------------------------

//  typedef void (base::*pFun)();
Derived1 d1;
Derived2 d2;
pFun pf1;
pf1=&Derived1::hello;
(&d1)->call(&d1,&Derived1::hello);

// (&d1)->call(&d1,&Derived1::world);

//  (&d1)->call(&d1,&base::hello);

//  (&d1)->call(&d1,&base::world);

call(&d1,&base::world);

call(&d1,&Derived1::hello);

call(&d1,&Derived1::world);

call(&d1,&base::hello);

call(&d1,&base::world);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: