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