在執行這個計劃,我得到以下編譯錯誤:爲什麼友元函數不能訪問類的私有成員
template.cpp: In function ‘std::istream& operator>>(std::istream&, currency&)’:
template.cpp:8: error: ‘int currency::doller’ is private
template.cpp:25: error: within this context
template.cpp:9: error: ‘int currency::cents’ is private
template.cpp:25: error: within this context
這是C++程序:
#include <iostream>
using namespace std;
class currency
{
private:
int doller;
int cents;
public:
currency():doller(0),cents(0) {}
friend ostream& operator<< (ostream& stream, const currency& c);
friend istream& operator>> (istream& in, const currency& c);
/*friend istream& operator>> (istream& in, const currency& c)
{
in >> c.doller >> c.cents;
return in;
} */
};
istream& operator>> (istream& in, currency& c)
{
in >> c.doller >> c.cents;
return in;
}
ostream& operator<< (ostream& stream, const currency& c)
{
stream << "(" << c.doller << ", " << c.cents << ")";
return stream;
}
template <class T>
void function(T data)
{
cout << "i am in generalized template function: " << data << endl;
}
template<>
void function (int data)
{
cout << "This is: specialized for int" << data << endl;
}
int main()
{
currency c;
cin >> c;
function (c);
function (3.14);
function ('a');
function (12);
return 0;
}
在同時的std :: ostream的&操作< <(STD :: ostream的&,常量貨幣&)不給任何錯誤。我想了解程序中是否有任何錯誤?
此外,雖然我給裏面的類的defition這是錯誤:
template.cpp: In function ‘std::istream& operator>>(std::istream&, const currency&)’:
template.cpp:18: error: ambiguous overload for ‘operator>>’ in ‘in >> c->currency::doller’
根據它的邏輯運算符貨幣不應該是const,因爲他在這個語句中修改它>> c.doller >> c.cents;因此,最好是改變朋友的簽名(忽略常數) –
@spin_eight當然,我已經改變了這一切。 – juanchopanza
感謝您的快速響應。 –