**C++,类模板作为基类派生某几个类,可不可以定义指向基类的指针,然后通过这个指针来指向各个派生类?大家帮忙解答一下。我是初学者,勿喷啊!** 以下面例子为例。C++的。
#include<iostream>
using namespace std;
template<class T1>
class A
{
protected:
T1 a;
public:
virtual void output1();
virtual void input();
virtual void output2();
};
template<class T1>
void A<T1>::output1()
{
cout<<"输入a:"<<endl;
}
template<class T1>
void A<T1>::input()
{
cin>>a;
}
template<class T1>
void A<T1>::output2()
{
cout<<a<<endl;
}
template<class T2>
class B:virtual public A<T2>
{
};
template<class T3>
class C:virtual public A<T3>
{
};
int main()
{
A<int> *pt;
B<int> B1;
C<double> C1;
int choice;
cout<<"chioce 1 or 2?"<<endl;
cin>>choice;
if(choice==1)
pt=&B1;
else
pt=&C1;
pt->output1();
pt->input();
pt->output2();
return 0;
}
--------------------Configuration: 38 - Win32 Debug--------------------
Compiling...
38.cpp
E:\SoftDocument\C++\38\38.cpp(58) : error C2440: '=' : cannot convert from 'class C *' to 'class A *'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
执行 cl.exe 时出错.
38.exe - 1 error(s), 0 warning(s)