我有以下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;
}
Run Code Online (Sandbox Code Playgroud)
在尝试编译时,我收到以下错误:
$ 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'
Run Code Online (Sandbox Code Playgroud)
我不明白为什么不Control
和Label
继承Surface
s属性?
Naw*_*waz 12
继承的成员不能出现在member-initialization-list中.试想一下,它们如何出现在派生类的成员初始化列表中,因为到它将被执行时,它们(即基类成员)已经被创建(回想一下基础子对象在派生类构造函数和成员之前创建) - 初始化列表).
如果它被允许,那么这意味着将允许基类成员被多次初始化,这没有意义.在C++中,对象不会多次初始化1次.初始化只发生一次; 任务可以多次发生.
编写代码的正确方法是参数化基类的构造,并通过的值x
和y
作为参数传递给基类的构造.
我的意思是动态初始化只发生一次.但是,一个对象可以初始化两次:一次在编译时称为静态初始化,然后在运行时称为动态初始化.有关更多信息,请参阅:c ++中对象的动态初始化是什么?
归档时间: |
|
查看次数: |
1978 次 |
最近记录: |