爲什麼C++約運算符重載
賦值運算符必須是 非靜態成員函數
運營商(),操作符[],並且操作符 - > 也必須被實現爲非易失靜態 成員函數。
例如
class IntList
{
private:
int m_anList[10];
public:
int& operator[] (const int nIndex);
};
int& IntList::operator[] (const int nIndex)
{
return m_anList[nIndex];
}
這是下標過載。它只能通過使用成員函數來重載。 它不能使用友元函數,如 超載,
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
// Overload -cCents
friend Cents operator-(const Cents &cCents);
};
// note: this function is not a member function!
Cents operator-(const Cents &cCents)
{
return Cents(-cCents.m_nCents);
}
向我們展示一些關於如何認爲它可能工作的代碼。最好的答案顯示並說明OP正在嘗試做什麼,並在問題發佈之前嘗試過。 – 2011-03-15 02:36:35
爲什麼?因爲它的C++定義! – AbiusX 2011-03-15 02:37:39