一个关于继承和虚函数的问题

首先,看一下这几行简单的代码:

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;
}

这次顺利编译通过。

所以得出的结论是:继承于非抽象类的子类,也可以通过在其内部声明纯虚函数而成为抽象类。

呵呵,关于我又想到了好几个问题,我在总结一下,下次写出问题和测试结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值