我有一個代表特殊數字的類。操作員作爲朋友重載函數?
class SecretInteger
{
private:
unsigned int *data;
size_t length;
public:
SecretInteger operator+(const SecretInteger other) const;
}
我不能讓我的代碼的任何其他部分可以訪問data
變量。但是,我的operator+
函數必須能夠看到它。通常在這種情況下,我知道使用關鍵字friend
是唯一的方法。然而,當我寫:
friend SecretInteger operator+(const SecretInteger other);
它聲稱,operator+
不能被聲明爲朋友,即使我以前寫過friend std::ostream& operator<<(std::ostream& stream, const SecretInteger val);
,它工作正常。
我必須提供給我什麼選擇?如果我有一個像
const *unsigned int getData() const;
的公共方法,我認爲即使如此,它實際上並沒有把這些變量返回const
吧?我真的不希望有一個getData()
方法,而是剛剛宣佈,有機會爲friend
的功能。
你聲明'運營商+'作爲一個成員函數,因此它可以訪問'data',不是嗎? – songyuanyao
~~它不能訪問'other'的數據,這使得我不可能執行算術~~ – Hatefiend
邊注:即使你堅持了過載的成員函數,沒有理由被接受的說法值。當然'const SecretInteger&other'就是你想要的。 – ShadowRanger