在C++11程序中,我想在派生类Derived中访问基类Base的成员b2,如下所示:
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声称,您只需访问基类的成员,而无需任何进一步的操作。这里也是: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'发布于 2020-05-11 12:56:06
如何访问派生类中的基类成员?
您可以通过指针或通过使用名称隐式地访问基类成员,除非名称是隐藏的。
是这样的:
派生(int b1,int b2):Base(b1),b2(b2) {} // error
虽然派生类可以访问基的成员,但它不能初始化成员。它只能作为一个整体初始化基,如果基有构造函数,那么该构造函数负责这些成员。
,谁能给我看看正确的语法吗?
没有语法可以进行这样的初始化。必须在基构造函数中初始化成员。
https://stackoverflow.com/questions/61730209
复制相似问题