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

C++虚方法疑问:派生类对象赋值基类后为何未调用派生类方法?

问题原因:对象切片

你写的代码里出现了对象切片的问题:

Base o = Derived();

当你把派生类对象直接赋值给基类对象时,派生类对象中超出基类的部分会被“切割”掉,最终o只是一个纯粹的基类对象,而非派生类对象。哪怕run是虚函数,也无法触发多态——因为多态需要通过指针或引用来指向派生类对象,才能在运行时动态绑定到派生类的函数。

修复方案

方案1:使用指针

#include <iostream>

using namespace std;

class Base
{
public:
    Base() {}
    virtual void run() {cout << "Running base method" << endl;}
    virtual ~Base() {}
};

class Derived : public Base
{
public:
    Derived() {}
    void run() {cout << "Running derived method" << endl;}
    ~Derived() {}
};

int main()
{
    Base* o = new Derived();
    o->run(); // 现在会输出"Running derived method"
    delete o; // 虚析构函数保证派生类析构逻辑被执行
    return 0;
}

方案2:使用引用

#include <iostream>

using namespace std;

class Base
{
public:
    Base() {}
    virtual void run() {cout << "Running base method" << endl;}
    virtual ~Base() {}
};

class Derived : public Base
{
public:
    Derived() {}
    void run() {cout << "Running derived method" << endl;}
    ~Derived() {}
};

int main()
{
    Derived d;
    Base& o = d;
    o.run(); // 现在会输出"Running derived method"
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:05:23