C++11:如何访问派生 class 中的基 class 成员?

C++11: How to access base class member in a derived class?

在 C++11 程序中,我想访问基 class 的成员 b2 Base 在派生的 class Derived 中像这样:

struct Base
{
    const int b1 = 0;
    const int b2 = 0;
    Base (int b1) : b1(b1) {} // ok
};

struct Derived : public Base
{
    Derived (int b1, int b2) : Base(b1), b2(b2) {} // error
    Derived (int b2) : Base(1), Base::b2(b2) {} // error
    Derived () : Base(1), this->b2(2) {} //error
};

线程 accessing base class public member from derived class 声称您可以访问基础 class 的成员而无需任何 废话不多说同样在这里:Accessing a base class member in derived class

有人可以告诉我正确的语法吗?

g++ 一直向我抛出错误:

main.cpp: In constructor 'Derived::Derived(int, int)':
main.cpp:10:42: error: class 'Derived' does not have any field named 'b2'
main.cpp: In constructor 'Derived::Derived(int)':
main.cpp:11:41: error: expected class-name before '(' token
main.cpp:11:41: error: expected '{' before '(' token
main.cpp: At global scope:
main.cpp:11:5: warning: unused parameter 'b2' [-Wunused-parameter]
main.cpp: In constructor 'Derived::Derived()':
main.cpp:12:27: error: expected identifier before 'this'
main.cpp:12:27: error: expected '{' before 'this'

How to access base class member in a derived class?

您可以 访问 基础 class 成员,可以通过 this 指针或隐含地使用名称,除非它是隐藏的。

like so:

Derived (int b1, int b2) : Base(b1), b2(b2) {} // error

虽然派生 class 可以 访问 基的成员,但它不能 初始化 它们。它只能将基类作为一个整体进行初始化,如果基类有一个构造函数,那么该构造函数负责那些成员。

So could someone show me the correct syntax please?

没有进行这种初始化的语法。您必须在基础的构造函数中初始化成员。