C++ 为什么friend函数不能访问类的私有成员
执行此程序时,我遇到以下编译错误:C++ 为什么friend函数不能访问类的私有成员,c++,templates,friend,C++,Templates,Friend,执行此程序时,我遇到以下编译错误: 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 curre
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;
}
您的
运算符>>
定义中的签名错误,这意味着您正在声明和定义不同的运算符。您需要从friend istream&operator
声明中删除const
,以便将其作为friend
运算符的定义:
friend
istream& operator>> (istream& in, currency& c)
//
不明确的重载也是出于同样的原因。您有两个匹配的函数。上述建议的修复将解决这两个问题。运算符的签名与声明为类的朋友的签名不匹配:
istream& operator>> (istream& in, currency& c); // outside class
istream& operator>> (istream& in, const currency& c); // friend class
// ^^^^^
您需要删除方法声明中的
const
签名:
friend istream& operator>> (istream& in, currency& c);
您定义的函数中没有
const
,因此它不是您声明为friend
的函数,因此无法访问private
成员。请注意,声明currency
对象const
也没有意义,因为您可以使用instream操作符对其进行更改。根据其操作符的逻辑,currency不应为const,因为他在>>c.doller>>c.cents中的此语句中对其进行了修改;所以最好更改朋友的签名(省略const)谢谢您的快速响应。谢谢,我的签名也不匹配。
friend istream& operator>> (istream& in, currency& c);