gpt4 book ai didi

c++ - 子类不继承祖 parent 属性

转载 作者:太空狗 更新时间:2023-10-29 23:28:33 24 4
gpt4 key购买 nike

我有以下 C++ 代码:

#include <iostream>
#include <string>
using namespace std;

class Surface
{
public:
virtual void draw();
protected:
int x,y;
};

class Control: public Surface
{
public:
Control(): x(10), y(10), name("control") { cout << "Control constructor" << endl; }
void draw() {}
protected:
string name;
};

class Label: public Control
{
public:
Label(): x(10), y(10), name("label"), text("label") { cout << "Label constructor" << endl; }
void draw() { cout << "drawing a label" << endl; }

protected:
string text;
};

int main(int argc, const char *argv[])
{
Label l;
return 0;
}

尝试编译时,出现以下错误:

$ g++ main.cpp
main.cpp: In constructor 'Control::Control()':
main.cpp:16:16: error: class 'Control' does not have any field named 'x'
main.cpp:16:23: error: class 'Control' does not have any field named 'y'
main.cpp: In constructor 'Label::Label()':
main.cpp:25:14: error: class 'Label' does not have any field named 'x'
main.cpp:25:21: error: class 'Label' does not have any field named 'y'
main.cpp:25:28: error: class 'Label' does not have any field named 'name'

我不明白为什么 ControlLabel 不继承 Surface 的属性?

最佳答案

继承的成员不能出现在成员初始化列表中。想一想,它们怎么会出现在派生类的成员初始化列表中,因为在执行它时,它们(即基类成员)已经创建(回想一下,基子对象是在派生类之前创建的构造函数和成员初始化列表)

如果允许,则意味着基类成员将被允许初始化 不止一次,这是没有意义的。在 C++ 中,对象初始化1 不会超过一次。初始化只发生一次;赋值可以发生多次。

编写该代码的正确方法是参数化基类构造函数,并将 xy 的值作为参数传递给基类构造函数。

1。我的意思是动态初始化只发生一次。但是,一个对象可以初始化两次:一次在编译时称为静态初始化,另一次在运行时称为动态初始化。有关更多信息,请参阅:What is dynamic initialization of object in c++?

关于c++ - 子类不继承祖 parent 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10268205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com