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

C++继承中const关键字使用问题:虚函数调用未触发多态

C++继承中const虚函数重写问题的解决

你的问题核心是const是成员函数签名的一部分:基类的virtual void pol() const和派生类的void pol()属于不同的函数,派生类并没有重写基类的虚函数,而是重载了一个新函数。当通过const Base*调用pol()时,编译器只会匹配基类的const版本,因此输出"Base"。

解决方法很简单:给派生类的pol()函数加上const修饰,让它的签名和基类的虚函数完全一致,这样就能正确完成重写:

#include <iostream>
using namespace std;

class Base {
public : 
    virtual void pol() const
    {
        cout<< " Base ";
    }
};

class Derived : virtual public Base {
public:
    void pol() const  // 添加const修饰,匹配基类虚函数签名
    {
        cout<< "derived";
    }
};

int main( )
{
    const Base *b = new Derived();
    b-> pol();  // 此时会调用派生类的重写版本,输出"derived"
    return 0;
}

额外说明:如果需要派生类同时支持const和非const对象调用不同的pol(),可以在派生类中同时定义两个版本,并且C++11及以后推荐用override关键字显式标记重写,避免签名不匹配的隐式错误:

class Derived : virtual public Base {
public:
    void pol() const override  // 重写基类的const虚函数
    {
        cout<< "derived const";
    }
    void pol()  // 重载的非const版本,仅对非const对象可见
    {
        cout<< "derived non-const";
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:30:53