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
相关产品推荐
相关产品推荐

