我刚刚开始了解朋友功能。 我按照教程之一,但无法使代码工作。 我猜想我犯了很多错误。
我的代码:
#include <iostream>
using namespace std;
class Sale
{
friend ostream& operator << (ostream, const Sale&);
int receiptNum;
double salesAmt;
public:
Sale(int,double);
};
Sale::Sale(int num,double sale)
{
receiptNum = num;
salesAmt = sale;
}
ostream operator << (ostream& out,const Sale aSale)
{
out << "Sale #" << aSale.receiptNum << " for $ " << aSale.salesAmt << endl;
return out;
}
int main()
{
Sale aShirt(1567,39.95);
cout << aShirt;
return 0;
}
错误
error: In function 'std::ostream operator<<(std::ostream&, Sale)'
error: 'int Sale::receiptNum' is private
error: 'double Sale::salesAmt' is private
error: 'std::ios_base::ios_base(const std::ios_base&)' is private
error: within this context|
error: ambiguous overload for 'operator<<' in 'std::cout << aShirt'
由于
答案 0 :(得分:2)
友元函数和您的实现使用不同的签名定义。所以这些是不同的(重载)函数:
friend ostream& operator << (ostream, const Sale&);
...
ostream operator << (ostream& out,const Sale aSale) { ... }
你必须对齐这两个签名,以便向你的编译器说明你说的是同一个函数:
friend ostream& operator << (ostream&, const Sale&);
...
ostream& operator << (ostream& out,const Sale &aSale) { ... }
这里的online demo可以按照您的预期运作。