16,472
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
template <typename T>
class Base
{
public:
Base()
{
cout << "Base::Base" << endl;
pT = static_cast<T*>(this);
}
void fun()
{
cout << "Base::fun" << endl;
}
void doSomething()
{
pT->fun();
}
private:
T* pT;
};
class Drive : public Base<Drive>
{
public:
Drive()
{
cout << "Drive::Drive" << endl;
}
void fun()
{
cout << "Drive::fun" << endl;
}
};
class Drive11 : public Base<Drive11>
{
public:
Drive11()
{
cout << "Drive11::Drive11" << endl;
}
void fun()
{
cout << "Drive11::fun11" << endl;
}
};
int main()
{
class A
{
virtual void fun(){}
};
class B:public A
{
virtual void fun()
};
class C:public A
{
virtual void fun()
};
A* P;
P = new B;
P = new C;
Drive* pDrive = new Drive;
pDrive->doSomething();
Drive11* pDrive11 =new Drive11;
pDrive11->doSomething();
return 0;
}
template <class T>
void doSomething()
{
Base<T> * P;
P = new T;
P->doSomething();
delete P;
}
//调用时:
doSomething<Drive>();
doSomething<Drive11>();