我想添加兩個對象,它們在同一個類中。運算符重載+添加兩個對象
在類的私有部分,我有兩個int
變量
class One {
private:
int num1, num2;
public:
One operator+=(const One&); // - a member operator that adds another One object - to the current object and returns a copy of the current object
friend bool operator==(const One&, const One&); // - a friend operator that compares two One class objects for equality
};
One operator+(const One&, const One&);// - a non-friend helper operator that adds One objects without changing their values and returns a copy of the resulting One
我不知道我有一個問題在opeartor+
我猜
One operator+(const One &a, const One &b){
One c,d,r;
c = a;
d = b;
r += b;
r += a;
return r;
}
我覺得上面的代碼錯誤,但我試圖使用像b.num1和我得到編譯錯誤
error: 'int One::num1' is private error: within this context
我也不能使用b-> num1,因爲上述函數不在成員函數部分。
error: base operand of '->' has non-pointer type 'const One'
這是它在main
Result = LeftObject + RightObject;
Whenever'operator +'錯了嗎?順便說一句:你忘了初始化成員。 –
@ user956030對不起? – Ali
你不能做'b.num1',''num1'是私人會員。如果你需要訪問它,你需要有一個* getter *函數。由於您尚未創建指針類型,因此'b->'無效。你打算添加私人整數? –