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

In a C++11 program I'd like to access the member b2 of a base class Base in a derived class Derived like so:

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
};

Thread accessing base class public member from derived class claims that you can just access base class's members without any further ado. Same here: 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'
评论
  • 小笨蛋o
    小笨蛋o 回复
    如何访问派生类中的基类成员?

    You can access the base class members either through this pointer or implicitly by using the name unless it is hidden.

    like so:

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

    虽然派生类可以访问基类的成员,但无法初始化它们。它只能初始化整个基础,如果基础具有构造函数,则该构造函数负责这些成员。

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

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