C++ 模板类继承
我对以下代码有一个问题(这是一个在我的程序中重现错误的非常简化的示例):C++ 模板类继承,c++,templates,inheritance,C++,Templates,Inheritance,我对以下代码有一个问题(这是一个在我的程序中重现错误的非常简化的示例): #包括 使用名称空间std; 模板类CBase { 公众: 模板CBase(constt2&x):\u var(x){;} 模板CBase(constcbase&x){u var=x.var();} ~CBase(){;} T var()常量{return_var;} 受保护的: T_var; }; 模板类C派生:公共CBase { 公众: 模板CDerived(constt2&x):CBase(x){;} 模板CDeri
#包括
使用名称空间std;
模板类CBase
{
公众:
模板CBase(constt2&x):\u var(x){;}
模板CBase(constcbase&x){u var=x.var();}
~CBase(){;}
T var()常量{return_var;}
受保护的:
T_var;
};
模板类C派生:公共CBase
{
公众:
模板CDerived(constt2&x):CBase(x){;}
模板CDerived(constcbase&x):CBase(x){;}
~CDerived(){;}
};
int main()
{
CBase-bd(3);
CBase bi(bd);//
如果要使代码正常工作,请执行以下操作:
首先是公开而不是私下
添加另一个以CDerived
为参数的构造函数
所以你需要这样做:
template<class T> class CDerived : public CBase<T> //derived publicly
{
public:
template <class T2> CDerived(const T2 &x) : CBase<T>(x) {;}
//add this constructor
template <class T2> CDerived(const CDerived<T2> &x) : CBase<T>(x.var()) {;}
template <class T2> CDerived (const CBase<T2> &x) : CBase<T>(x) {;}
~CDerived() {;}
};
模板类CDerived:public CBase//公开派生
{
公众:
模板CDerived(constt2&x):CBase(x){;}
//添加此构造函数
模板CDerived(constcderived&x):CBase(x.var()){;}
模板CDerived(constcbase&x):CBase(x){;}
~CDerived(){;}
};
它现在应该可以工作了:尝试创建另一个构造函数,该构造函数在基类中接受泛型对象,并使用动态强制转换来赋值
template <class T2> CBase (const Object &x) : _var() {
try {
const CBase<T2> &x_casted = dynamic_cast<const CBase<T2> &> (x);
_var = x_casted.var();
}
catch {
std::cerr << "Object not of type CBase" << std::endl;
}
}
模板CBase(const Object&x):\u var(){
试一试{
常量CBase&x_casted=动态_cast(x);
_var=x_casted.var();
}
抓住{
是的,我理解。我的问题是:如何修改基类,使其能够从CDerive中构造CDerive?@Vincent:您是从CBase中私下派生的。这是有意的还是仅仅是一个错误?非常有趣。但它调用了第一个构造函数(这个例子很好,但在我的程序中我需要调用第二个)。受你的代码启发,我尝试了:模板CDerived(const CDerived&x):CBase(static_cast(x)){;}。它可以编译,但你认为这是一个好方法吗?@Vincent:这也应该可以。事实上,这是一个好方法。
template <class T2> CDerived(const CDerived<T2> &x) : CBase<T>(static_cast<const CBase<T2>&>(x)) {;}
CDerived<int> di(dd1); // <- The problem is here
CDerived<int> di(dd1); // <- The problem is here
^ ^
| |
| this helps compiler to deduce T2 as double
|
this is T of the CDerived as well as of CBase
template<class T> class CDerived : public CBase<T> //derived publicly
{
public:
template <class T2> CDerived(const T2 &x) : CBase<T>(x) {;}
//add this constructor
template <class T2> CDerived(const CDerived<T2> &x) : CBase<T>(x.var()) {;}
template <class T2> CDerived (const CBase<T2> &x) : CBase<T>(x) {;}
~CDerived() {;}
};
template <class T2> CBase (const Object &x) : _var() {
try {
const CBase<T2> &x_casted = dynamic_cast<const CBase<T2> &> (x);
_var = x_casted.var();
}
catch {
std::cerr << "Object not of type CBase" << std::endl;
}
}