[英]C++11: How to access base class member in a derived class?
在 C++11 程序中,我想在派生的 class 中访问基础Base
的成员b2
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
};
从派生的 class 访问基 class 公共成员的线程声称您可以轻松访问基类的成员。 此处相同: 访问派生 class 中的基本 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'
如何访问派生 class 中的基本 class 成员?
您可以通过this
指针或使用名称隐式访问基本 class 成员,除非它被隐藏。
像这样:
Derived (int b1, int b2): Base(b1), b2(b2) {} // error
虽然派生的 class 可以访问基类的成员,但它不能初始化它们。 它只能将基础作为一个整体进行初始化,如果基础有构造函数,那么该构造函数负责那些成员。
那么有人可以告诉我正确的语法吗?
没有语法来进行这种初始化。 您必须在基的构造函数中初始化该成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.