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

C++菱形继承下,子类有同名成员时如何访问祖父类成员?

解决菱形继承中同名成员的访问问题

你的代码里,Child类同时拥有自身的私有成员name,以及通过虚继承从GrandParent类继承来的同名name成员。要正确区分这两个成员,需要借助作用域限定符来明确指定访问的是哪一个:

修改后的拷贝赋值运算符代码

Child & Child::operator=(const Child & other)
{
    std::cout << "Child Copy assignment operator called" << std::endl;
    if (this != &other)
    {
        // 访问Child类自身的name成员
        this->name = other.name;
        // 或者更明确的写法:Child::name = other.Child::name;
        
        // 访问GrandParent类继承来的name成员
        GrandParent::name = other.GrandParent::name;
        GrandParent::age = other.age;
    }
    return (*this);
}

关键说明

  • 直接写name(或this->name)时,编译器会优先匹配当前类(Child)的成员,所以这是访问Child自己的name。如果想让代码更清晰,也可以用Child::name来明确指定。
  • 要访问GrandParent中的name,必须使用GrandParent::作用域限定符。由于你用了虚继承,GrandParent的成员只会存在一份实例,通过这个限定符就能准确访问到基类的同名成员,避免和子类成员混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 01:32:01