首先大家来看这段代码:
class A
{
public:
void Show()
{
cout << "A::Show() !!!" << endl;
}
void Fun()
{
cout << "A::Fun() !!! " << endl;
}
};
class B
{
public:
void Show()
{
cout << "B::Show() !!!" << endl;
}
void Fun()
{
cout << "B::Fun() !!! " << endl;
}
};
class C
{
public:
void Show()
{
cout << "C::Show() !!!" << endl;
}
void Fun()
{
cout << "C::Fun() !!! " << endl;
}
};
template<typename Com>
class Test
{
public:
void send()
{
Com c;
c.Show();
c.Fun();
}
void Show()
{
cout << "Test::Show() !!!" << endl;
}
};
int main(int argc,char**argv)
{
Test<A> t1;
t1.send();
t1.Show();
cout << endl;
Test<B> t2;
t2.send();
t2.Show();
cout << endl;
Test<C> t3;
t3.send();
t3.Show();
cout << endl;
return 0;
}
我们先来大概分析一下这段没有实际意义的代码:
首先定义了类A,类B,类C,这三个类都具有Show方法和Fun方法,只不过具体的实现不同。接着又定义了模板类Test。
下来我们看程序的执行结果:
上面的代码我们并没有使用继承,通过模板类Test的类型,使得函数的调用不同。。。
下面我们来看如何通过继承来实现: