[英]Why does my compiler insist that operator<< has 3 parameters when it has 2?
这看起来很简单,我之前已经重载了运算符,但现在我收到错误消息error: overloaded 'operator<<' must be a binary operator (has 3 parameters)
。 我觉得我缺少一些明显的东西,但是在谷歌搜索了几个小时后,我似乎无法弄清楚......在 my.h 文件中我有这个
class NeuralNet{
private:
vector<Layer*> layers;
public:
NeuralNet(){}
void addLayer(Layer*);
friend ostream& operator<<(ostream&, const NeuralNet);
};
在 my.cpp 文件中我有这个
ostream& NeuralNet::operator<<(ostream& os, NeuralNet& net){
for (Layer* l : net.layers){
os << l->getSize() << " ";
}
os << "\n";
for (Layer* l : net.layers){
os << l->getInputSize() << " ";
}
os << endl;
return os;
}
Layer
目前是一个 dummy-class,getInputSize() 和 getSize() 只是返回int
,不涉及自定义命名空间。 我想保持vector<Layer*> layers
私有,并且我之前使用friend
编写了代码,以便允许operator<<
访问私有变量。 但是现在,如果我不将operator<<
声明为friend
并删除.cpp 文件中的 NeuralNet NeuralNet::
我(显然)得到错误error: 'layers' is a private member of 'NeuralNet'
,但是当我包括我收到了错误消息。
ostream& NeuralNet::operator<<(ostream& os, NeuralNet& net){ ... }
需要是
ostream& operator<<(ostream& os, NeuralNet& net){
因为你已经宣布它是friend
function,而不是成员 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.