在类中要实现动态调用,需要使用数字成员指针和成员函数指针。
#include
#include
using namespace
std;
class
Transport
{
public:
Transport(double s,double
w)
{
Speed=s;
Weight=w;
}
virtual
~Transport()
{
cout<<"in
~Transport!"<<endl;
}
void
Move()
{
cout<<"in
moving"<<"\nSpeed="<<Speed<<"\nWeight="<<Weight<<endl;
}
void
setSpeed(double s)
{
Speed=s;
}
void
setWeight(double w)
{
Weight=w;
}
double
Speed;
double
Weight;
};
typedef
double Transport::*pdouble;//数字成员指针别名
typedef void
(Transport::*pSub)(double);//带参成员函数指针别名
typedef void
(Transport::*pMove)();//无参成员函数指针别名
void
main()
{
Transport
t(8.8,9.9);
//数字成员指针指向Speed;
pdouble
pd=&Transport::Speed;
printf("pd=%d\n",pd);
cout<<"Speed="<<t.*pd<<endl;
//数字成员指针指向Weight;
pd=&Transport::Weight;
printf("pd=%d\n",pd);
cout<<"Weight="<<t.*pd<<endl;
Transport
*pt=&t;
cout<<"调用带参成员函数指针指向setSpeed(double)"<<endl;;
pSub
ps=&Transport::setSpeed;
(pt->*ps)(88.88);
cout<<"调用带参成员函数指针指向setWeight(double)"<<endl;;
pSub
pw=&Transport::setWeight;
(pt->*pw)(99.99);
cout<<"调用无参成员函数指针指向Move()"<<endl;;
pMove
pm=&Transport::Move;
(pt->*pm)();
}
