使用带有继承变量的初始值设定项列表

发布于 2024-11-14 23:12:34 字数 399 浏览 4 评论 0原文

我已经摆弄一个程序大约 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

素食主义者 2024-11-21 23:12:34

一个对象只能初始化一次:当它第一次存在时。

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 of A because the member variable was already initialized by the constructor of A.

(In this specific case, technically i is left uninitialized because A did not initialize it; that said, it is still A's responsibility to initialize its member variables.)

雨落星ぅ辰 2024-11-21 23:12:34

在 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.

知足的幸福 2024-11-21 23:12:34

您必须在类 A 中定义带参数的公共构造函数。然后在类 B 中使用基类的构造函数。
例子:

#include <iostream>
using namespace std;

class A {
protected:
    int i;
public:
    A(int number) : i(number) {}
};

class B : public A {
public:
    B() : A(45) { }
};

int main() {
    B b;
}

You must define public constructor with parameter in class A. Then in class B use to constructor from base class.
Example:

#include <iostream>
using namespace std;

class A {
protected:
    int i;
public:
    A(int number) : i(number) {}
};

class B : public A {
public:
    B() : A(45) { }
};

int main() {
    B b;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文