試圖研究C++函數模板。作爲其中的一部分,我有下面的代碼。它工作正常,但我有如下問題: -關於重載運算符的問題<<
1]爲什麼運營商< <重載功能需要的朋友?如果我刪除關鍵字朋友,它會給編譯錯誤說:操作員< <有太多的參數。
2]爲什麼運算符重載函數需要返回一個對它的輸入參數的ostream對象的引用呢?
3]我懷疑這個,但是上面的兩個問題是否與事實有關:函數模板用於已經重載函數的用戶定義的類的事實?
template <class T>
T Average(T *atArray, int nNumValues)
{
T tSum = 0;
for (int nCount=0; nCount < nNumValues; nCount++)
tSum += atArray[nCount];
tSum /= nNumValues;
return tSum;
}
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents)
: m_nCents(nCents)
{
}
//Why is friend needed below
//Why does it need to return ostream&, why can't it have void return type, as all it is doing is printing the class private member.
friend ostream& operator<< (ostream &out, const Cents &cCents)
{
out << cCents.m_nCents << " cents ";
return out;
}
/*
void operator <<(const Cents &cCents) //did not work - compilation errors
{
cout << cCents.m_nCents << " cents ";
}
*/
void operator+=(Cents cCents)
{
m_nCents += cCents.m_nCents;
}
void operator/=(int nValue)
{
m_nCents /= nValue;
}
};
int main()
{
int anArray[] = { 5, 3, 2, 1, 4 };
cout << Average(anArray, 5) << endl;
double dnArray[] = { 3.12, 3.45, 9.23, 6.34 };
cout << Average(dnArray, 4) << endl;
Cents cArray[] = { Cents(5), Cents(10), Cents(15), Cents(14) };
cout << Average(cArray, 4) << endl;
cin.get();
return 0;
}
感謝。我有一個疑問,就是爲什麼不能做一個類成員函數。因爲最後這就是我要使用operator << with,用戶定義的類的對象,不是它。爲什麼它需要成爲非會員/一般功能? – goldenmean
@goldenmean:我的答案的第一部分涉及到這一點,您應該通讀我添加到答案中的鏈接,以幫助您更好地理解這一點,並解決您的疑問。 –