我正在寫一類是這樣的:超負荷運營商=在C兩個參數++
class Digit
{
private :
int *ref;
public :
Digit (int a) : ref(&a) {}
int get_val()
{
return (*ref);
}
Digit operator= (int &a)
{
if (a < 0 || a > 9)
throw "invalid digit assignment.";
(*ref) = a;
return (*this);
}
};
所以,如果有人定義了一個數字,他不能將超過9或低於0到它的價值。 問題是,我還想定義另一個=運算符,他也可以將一個數字分配給某個值。 我想是這樣的:
int operator= (int &a, Digit &d)
{
a = d.get_value();
return a;
}
,但我得到了一些錯誤:'int operator=(int&, Digit&)' must be a nonstatic member function
我怎樣才能解決這一問題?我如何重載operator = 2個參數?
爲什麼'ref'是*指針*? (只要構造函數返回,它也是無效的。) – molbdnilo
不要想「如何重載賦值運算符」,請考慮「我怎樣才能隱式地將'Digit'轉換爲'int'」。 – molbdnilo
@molbdnilo我不得不用[]運算符編寫一個返回數字的類,以便我們可以使用它:a [10] = 5; (和一些成員變更爲5.) – iambb5445