我正在学习c++继承,并在下面的练习中遇到问题,以创建具有特定需求的基类A和派生类B。我的答案写在下面,但似乎有一些问题。在这篇文章的结尾,我还有几个问题要问。

class A {
private:
int x;
protected:
A (): x(0) { }
A (int n): x(n) { }
int get() const {return x;}
public:
virtual void foo() = 0;
};

class B : public A {
public:
B (): { A(); }
B (int n): { A(n); }
virtual void foo() { std::cout << get();}
};我的问题是:
我确信我的代码写得不正确,但是谁能告诉我incorrect?
x在A中是私有的,B就不能继承那个数据成员了。那么B如何能够调用构造函数呢?
A是一个抽象类,但B也是一个抽象类吗?发布于 2019-11-22 08:01:24
- First you have an empty constructor initializer list in the `B` constructors. That will lead to build errors.
- Then in the `B` constructor the statement `A()` creates a temporary `A` object, which is promptly discarded and destructed. You need to "call" the parent class constructor from the `B` constructor initializer list:B():A() { /*空*/ }
您也打算对参数化的B构造函数执行同样的操作。
private成员,但是protected是可以的。这就是现在使用members.protected:子类可以访问基类保护的protected,您用一个实现覆盖foo,B不是抽象的,没有public的抽象成员https://stackoverflow.com/questions/58989828
复制相似问题