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

问题描述 投票:0回答:1

在一个C++11的程序中,我想访问基类中的成员 b2 基类Base 衍生类 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
};

线程 从派生类访问基类公共成员 声称你可以直接访问基类的成员,而不需要任何进一步的努力。这里也一样。在派生类中访问基类成员.

谁能告诉我正确的语法?

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'
c++ c++11 syntax constructor derived-class
1个回答
3
投票

如何在派生类中访问基类成员?

你可以 访问 的基类成员,或者通过 this 指针,或者通过使用名称来隐含,除非它被隐藏。

像这样。

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

当派生类可以 访问 基地的成员,它不能 初始化 它们。它只能初始化整个base,如果base有构造函数,那么这个构造函数就对这些成员负责。

那么谁能告诉我正确的语法呢?

没有任何语法可以做这样的初始化。你必须在base的构造函数中初始化成员。

© www.soinside.com 2019 - 2024. All rights reserved.