首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

问一个简单的要死的有关问题,关于简单的模板调用的

2013-08-01 
问一个简单的要死的问题,关于简单的模板调用的#include stdafx.h#include iostreamusing namespace st

问一个简单的要死的问题,关于简单的模板调用的


#include "stdafx.h"
#include "iostream"
using namespace std;


template<class T>
class CComObject : public T
{
public:
CComObject()  { }
~CComObject() { }

void CallBaseMethod()
{
T* pT = static_cast<T *>(this);
pT->BaseMethod();
}
private:

};


class Base
{
public:
Base()  { }
~Base() { }

void BaseMethod()
{
cout << "BaseMethod in Base" << endl;
}
};


class Math : public Base
{
public:
Math() { }
~Math(){ }

void BaseMethod()
{
cout << "BaseMethod in Math" << endl;
}
};


int _tmain(int argc, _TCHAR* argv[])
{
CComObject<Math>* pMath = new CComObject<Math>;
pMath->CallBaseMethod();
delete pMath;

Math *test = new Math;
(static_cast<Base *>(test))->BaseMethod();

return 0;
}


上面是我的代码,但是照理来说CallBaseMethod在调用的时候pT,应该已经是Base了才对,而他执行BaseMethod,为什么还是这段?cout << "BaseMethod in Math" << endl;?

比较菜,想不明白! 模板 类
[解决办法]
pT 的类型是 T*, T 就是模板参数, 这里 CComObject<Math>*?pMath 的模板参数是 Math, 所以 pT 就是 Math* 了. 自然调用到 Math 类的函数.
[解决办法]
你的这个问题在这里:
http://bbs.csdn.net/topics/190129363
[解决办法]
引用:
Quote: 引用:

pT 的类型是 T*, T 就是模板参数, 这里 CComObject<Math>*?pMath 的模板参数是 Math, 所以 pT 就是 Math* 了. 自然调用到 Math 类的函数.


那要如何才能调用这个类的父类?

多给个表示基类的模板参数, 然后里面使用这个内息

热点排行