加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 多级继承和纯虚函数

发布时间:2020-12-16 10:51:18 所属栏目:百科 来源:网络整理
导读:包含纯虚函数的类不能包含对象.这是我对纯虚函数的看法.我有以下程序,它编译没有任何错误. #includeiostreamusing namespace std;class Father { public: virtual void foo()=0;};class Son:public Father { // Nothing here };int main() {} 这是预期的,因
包含纯虚函数的类不能包含对象.这是我对纯虚函数的看法.我有以下程序,它编译没有任何错误.

#include<iostream>

using namespace std;

class Father {
   public:
   virtual void foo()=0;
};

class Son:public Father {
  // Nothing here 
};

int main() {

}

这是预期的,因为这两个类都没有对象.但是当我试图从包含纯虚函数的类中获得多级继承时,下面的程序给了我错误.

#include<iostream>

using namespace std;

class Father {
   public:
   virtual void foo()=0;
};

class Son:public Father {
  // Nothing here
};

class Grand_Son:public Son {
    void foo() {
        cout<<"nFunction foo From Grand_Sonn";
    }
};

int main() {
   Grand_Son x;
   x.foo();
}

错误如下所示.

In function 'int main()':|
|error: 'virtual void Grand_Son::foo()' is private|
|error: within this context|
||=== Build finished: 2 errors,0 warnings ===|

错误是出乎意料的,因为我继承了Son和Grand_Son这两个类.

是否可以使用涉及纯虚函数的类进行多级继承?

有什么建议?谢谢.

解决方法

class Grand_Son:public Son {
   public:
---^^^^^^^
    void foo() {
        cout<<"nFunction foo From Grand_Sonn";
    }
};

你没有宣布foo公开 – 我在上面添加了它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读