首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++11:如何访问派生类中的基类成员?

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

Stack Overflow用户
提问于 2020-05-11 12:52:59
回答 1查看 504关注 0票数 0

在C++11程序中,我想在派生类Derived中访问基类Base的成员b2,如下所示:

代码语言:javascript
复制
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++不断地向我抛错误:

代码语言:javascript
复制
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'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-11 12:56:06

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

您可以通过指针或通过使用名称隐式地访问基类成员,除非名称是隐藏的。

是这样的:

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

虽然派生类可以访问基的成员,但它不能初始化成员。它只能作为一个整体初始化基,如果基有构造函数,那么该构造函数负责这些成员。

,谁能给我看看正确的语法吗?

没有语法可以进行这样的初始化。必须在基构造函数中初始化成员。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61730209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档