使用带有继承变量的初始值设定项列表
我已经摆弄一个程序大约 20 分钟,我发现由于某种原因它不允许我在初始化列表中使用继承的变量。例如这个程序:
class A {
protected:
int i;
};
class B : public A {
public:
B() : i(45) { }
};
int main() {
B b;
}
会给出错误
错误:类“B”没有任何名为“i”的字段
但是,如果将构造函数更改为:
B() { i = 45; }
它会编译。
我从来不知道你不能初始化继承的变量。我的问题是,为什么?
I've been fiddling with a program for about 20 minutes and I found that for some reason it won't let me use inherited variables in initialization lists. This program, for example:
class A {
protected:
int i;
};
class B : public A {
public:
B() : i(45) { }
};
int main() {
B b;
}
Will give the error
error: class ‘B’ does not have any field named ‘i’
However, if you change the constructor to this:
B() { i = 45; }
It compiles.
I never knew you can't initialize inherited variables. My question is, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个对象只能初始化一次:当它第一次存在时。
A
在其构造函数中初始化其所有成员变量(在执行其构造函数主体之前)。因此,B
无法初始化A
的成员变量,因为该成员变量已由A
的构造函数初始化。(在这种特定情况下,从技术上讲,
i
未初始化,因为A
没有初始化它;也就是说,A
仍然有责任初始化其成员变量。)An object can only be initialized once: when it first comes into existence.
A
initializes all of its member variables in its constructor (before the body of its constructor is executed). Thus,B
cannot initialize a member variable ofA
because the member variable was already initialized by the constructor ofA
.(In this specific case, technically
i
is left uninitialized becauseA
did not initialize it; that said, it is stillA
's responsibility to initialize its member variables.)在 C++ 中你不能这样做。正常的方法是在父类中有一个(
protected
)构造函数,它接受一个用于设置变量的参数。几乎从不建议使用这样的受保护属性,因为它会让子类违反父类不变量,这只会在以后引起严重的调试麻烦。
You can't do this in C++. The normal way is to have a (
protected
) constructor in the parent class that takes a parameter used to set the variable.Using protected attributes like this is almost never suggested because it lets child classes violate parent class invariants which is only going to caused severe debugging headaches later on.
您必须在类 A 中定义带参数的公共构造函数。然后在类 B 中使用基类的构造函数。
例子:
You must define public constructor with parameter in class A. Then in class B use to constructor from base class.
Example: