You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中能否通过子类对象调用被重写的父类同名成员方法?

问题解答

这个需求完全可以实现,你遇到编译错误是因为作用域解析符::的使用顺序错误。

错误原因

mother::rita.display()的写法不符合C++语法规则:作用域解析符是用来指定成员所属的类域,而非指定对象所属的类,你需要把类域限定符放在要调用的成员方法前面,而不是对象名前面。

正确写法

把出错的那一行替换为:

rita.mother::display();

原理说明

因为daughter类是public继承mother类,子类对象内部会包含完整的父类子对象,子类定义的同名display()方法只是隐藏了父类的同名方法,并没有将其删除。显式指定mother::域后,编译器就会跳过子类的同名方法查找逻辑,直接调用父类的display()实现。

其他可选实现方式

你也可以通过显式类型转换,将子类对象转为父类的引用/指针后调用父类方法,效果完全一致:

// 引用转换
static_cast<mother&>(rita).display();
// 指针转换
static_cast<mother*>(&rita)->display();

修正后的完整可运行代码

#include <iostream>

using namespace std;

class mother{
    public:
    void display(){
        cout<<"Mother"<<endl;
    }
};
class daughter : public mother{
    public:
    void display(){
        cout<<"Daughter"<<endl;
    }
};

int main(){
    daughter rita;
    rita.display(); // 输出 Daughter
    rita.mother::display(); // 输出 Mother
    return 0;
}

内容的提问来源于stack exchange,提问作者simransharma3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:06:04