首先,看一下这几行简单的代码:
class A
{
int a;
public:
A(int aa):a(aa){};
void funa(){ a++;};
};
class B:public A
{
int b;
public:
B(int aa,int bb):A(aa),b(bb){};
virtual void funb()=0;//pure virtual function
};
class C
{
int c;
public:
C(int cc):c(cc){};
virtual void func()=0;
};
A a(1);//应该正确
C c(1);//应该错误
B b(1,2);//对不对呢?
在C++语言中,拥有纯虚函数的类成为抽象类,该类不能实例化一个对象,必须在进一步继承中实现该函数,然后用派生类定义对象。那么,现在的问题是,基类为非抽象类,从他继承来的类是不是非抽象类呢?如果该继承类有纯虚函数,又属于抽象类还是非抽象类呢?还是先测试一下上面代码,看看结果:
第一次测试:(使用VC++6.0)
int main(int argc, char* argv[])
{
A a(1);
C c(1);
B b(1,2);
}
看看结果:
F:/work2000/ddd/ddd.cpp(29) : error C2259: 'C' : cannot instantiate abstract class due to following members:
F:/work2000/ddd/ddd.cpp(20) : see declaration of 'C'
F:/work2000/ddd/ddd.cpp(29) : warning C4259: 'void __thiscall C::func(void)' : pure virtual function was not defined
F:/work2000/ddd/ddd.cpp(24) : see declaration of 'func'
F:/work2000/ddd/ddd.cpp(29) : error C2259: 'C' : cannot instantiate abstract class due to following members:
F:/work2000/ddd/ddd.cpp(20) : see declaration of 'C'
F:/work2000/ddd/ddd.cpp(29) : warning C4259: 'void __thiscall C::func(void)' : pure virtual function was not defined
F:/work2000/ddd/ddd.cpp(24) : see declaration of 'func'
F:/work2000/ddd/ddd.cpp(30) : error C2259: 'B' : cannot instantiate abstract class due to following members:
F:/work2000/ddd/ddd.cpp(12) : see declaration of 'B'
F:/work2000/ddd/ddd.cpp(30) : warning C4259: 'void __thiscall B::funb(void)' : pure virtual function was not defined
F:/work2000/ddd/ddd.cpp(17) : see declaration of 'funb'
F:/work2000/ddd/ddd.cpp(30) : error C2259: 'B' : cannot instantiate abstract class due to following members:
F:/work2000/ddd/ddd.cpp(12) : see declaration of 'B'
F:/work2000/ddd/ddd.cpp(30) : warning C4259: 'void __thiscall B::funb(void)' : pure virtual function was not defined
F:/work2000/ddd/ddd.cpp(17) : see declaration of 'funb'
Error executing cl.exe.
定义抽象类C 的对象肯定是错的,去掉C对象的定义,而编译结果也显示了B为抽象类。
再用D继承B,使其成为非抽象类
class D:public B
{
int d;
public:
D(int dd,int bb,int aa):B(bb,aa),d(dd){};
void fund(){d++;};
void dunb(){d--;};
};
int main(int argc, char* argv[])
{
A a(1);
//C c(1);
// B b(1,2);
D d(1,2,3);
return 0;
}
这次顺利编译通过。
所以得出的结论是:继承于非抽象类的子类,也可以通过在其内部声明纯虚函数而成为抽象类。
呵呵,关于我又想到了好几个问题,我在总结一下,下次写出问题和测试结果