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

C++运算符重载时无法访问类私有成员报错问题求解

问题原因

两个报错均由运算符重载函数的定义语法错误导致,没有正确将函数声明为Rectangle类的成员函数:

  • 报错1「标识符width_未定义」:你写的Rectangle::Rectangle operator + (const Rectangle& rec) 被编译器识别为全局函数,全局函数没有类的this指针,无法直接访问类的成员变量width_。
  • 报错2「成员'Rectangle::width_'不可访问」:类的private成员仅允许类自身的成员函数/友元访问,全局函数无访问权限,因此无法读取参数rec的私有成员width_。

另外你的代码还存在笔误:成员变量length_被误写为length,修正语法后也需要同步修改。

修正方案

运算符重载作为类成员函数时,作用域解析符::需要加在函数名operator+/operator-前面,而非返回值前面,修正后的cpp源文件代码如下:

// 构造函数无需修改
Rectangle::Rectangle(double width, double length){
    width_ = width;
    length_ = length;
}

// 修正运算符+的定义语法
Rectangle Rectangle::operator + (const Rectangle& rec){
    Rectangle rect(width_ + rec.width_, length_ + rec.length_);
    return rect;
}
// 修正运算符-的定义语法
Rectangle Rectangle::operator - (const Rectangle& rec){
    Rectangle rect(width_ - rec.width_, length_ - rec.length_);
    return rect;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:45:06