尝试学习C ++函数模板。以下是我所学的一部分代码。它可以正常工作,但我有以下问题:
1]为什么运算符<<重载函数需要是友元?如果我删除关键字friend,它会给出编译错误,说operator<<具有太多参数。
2]为什么运算符<<重载函数需要返回对ostream对象的引用,该对象也是其输入参数?
3]我怀疑这个问题,但以上两个问题是否与使用函数模板用于具有重载函数的用户定义类有任何关系?
1]为什么运算符<<重载函数需要是友元?如果我删除关键字friend,它会给出编译错误,说operator<<具有太多参数。
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;
}