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

如何仅赋值C++子类属性而不修改父类属性?

仅赋值子类属性不影响父类的解决方案

现有如下Parent和Child类定义:

class Parent
{
private:
    int m_nParentX;
public:
    Parent(int nX)
    {
        m_nParentX = nX;
    }
    int GetParentX()
    {
        return m_nParentX;
    }
};
class Child : public Parent
{
private:
    int m_nChildY;
public:
    Child(int nX, int nY) : Parent(nX)
    {
        m_nChildY = nY;
    }
    int GetChildY()
    {
        return m_nChildY;
    }
};

创建实例后直接执行*b = *a,会导致b的父类属性被a的父类属性覆盖,不符合“仅复制子类属性、保留父类原有值”的需求。以下是几种可行的解决方案:

方案一:重载Child类的赋值运算符

C++默认的赋值运算符会逐成员复制对象的所有部分(包括继承自父类的成员),我们可以自定义赋值运算符,只处理子类自身的属性:

class Child : public Parent
{
private:
    int m_nChildY;
public:
    Child(int nX, int nY) : Parent(nX)
    {
        m_nChildY = nY;
    }
    int GetChildY()
    {
        return m_nChildY;
    }

    // 自定义赋值运算符,仅复制子类成员
    Child& operator=(const Child& other) {
        m_nChildY = other.m_nChildY;
        return *this;
    }
};

修改后,调用*b = *a时只会复制m_nChildY,b的父类属性m_nParentX会保持原值。

方案二:添加专门的成员函数复制子类属性

如果不想修改默认赋值运算符的语义,可以给Child类添加一个语义明确的成员函数,专门负责复制子类属性:

class Child : public Parent
{
private:
    int m_nChildY;
public:
    Child(int nX, int nY) : Parent(nX)
    {
        m_nChildY = nY;
    }
    int GetChildY()
    {
        return m_nChildY;
    }

    void CopyChildProperties(const Child& other) {
        m_nChildY = other.m_nChildY;
    }
};

使用时直接调用该函数即可:

b.CopyChildProperties(a);

方案三:手动赋值(适合属性较少的场景)

如果子类只有少量属性,可以通过添加setter方法手动赋值,这种方式虽然简单但扩展性较差:

class Child : public Parent
{
private:
    int m_nChildY;
public:
    Child(int nX, int nY) : Parent(nX)
    {
        m_nChildY = nY;
    }
    int GetChildY()
    {
        return m_nChildY;
    }
    // 添加setter方法
    void SetChildY(int y) {
        m_nChildY = y;
    }
};

// 使用时直接调用setter
b.SetChildY(a.GetChildY());

以上任意方案都能实现期望的输出:

10:20   30:40
10:20   30:20

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:58:22