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

Derived类中接受并返回Base引用的operator=能否合法调用?

关于Derived类中Base& operator=(const Base&)的合法调用场景分析

先贴出原代码:

class Base
{
public:
    Base() = default;
};

class Derived : public Base
{
public:
    Derived() = default;
    std::string m_test;
    
    Base& operator=(const Base& other)
    {
        const Derived *pThat = (Derived*)&other;
        m_test = "Woo";
        return *this;
    }
};

这个赋值运算符确实存在合法调用的场景,核心是让传入的other引用/指针实际绑定的是Derived类型的对象,而非纯Base对象:

  • 直接用绑定到Derived对象的Base引用赋值
    比如写这样的代码:

    Derived d1, d2;
    Base& b_ref = d2; // b_ref是Base类型引用,但实际指向Derived对象
    d1 = b_ref;       // 这里会调用Derived类中定义的Base& operator=(const Base&)
    

    此时other的动态类型是Derived,C风格强制转换(Derived*)&other是合法且安全的(本质是把Base指针转换回它原本的Derived指针类型)。

  • 通过Base指针指向Derived对象进行赋值
    再比如:

    Derived d1;
    Base* b_ptr = new Derived(); // b_ptr指向Derived对象
    d1 = *b_ptr;                 // 调用该赋值运算符
    delete b_ptr;
    

    同样,*b_ptr的动态类型是Derived,转换合法,代码能正常执行。

需要注意的是,如果传入的other是纯Base对象(比如直接定义Base b; d1 = b;),那强制转换就是未定义行为,这也是原代码的风险点,但确实存在上面两种合法调用的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:05:29