为什么我的编译器坚持 operator<<有3个参数,而它只有2个?

问题描述 投票:0回答:1

这看起来很简单,我以前也重载过运算符,但现在我得到的错误信息是 error: overloaded 'operator<<' must be a binary operator (has 3 parameters). 我觉得有一些明显的东西,我错过了,但在google了几个小时,我似乎无法弄清楚...... 在我的.h文件中,我有这个

class NeuralNet{
    private:
        vector<Layer*> layers;
    public:
        NeuralNet(){}
        void addLayer(Layer*);
        friend ostream& operator<<(ostream&, const NeuralNet);
};

在我的.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目前是一个虚类,getInputSize()和getSize()只是返回了 int的,不涉及自定义的命名空间。我想保留 vector<Layer*> layers 私有的,我之前用 friend 以致于 operator<< 可以允许访问私有变量。但是现在,如果我不声明 operator<< 作为 friend 并去除 NeuralNet:: 在.cpp文件中,我(很明显)得到了以下错误信息 error: 'layers' is a private member of 'NeuralNet'但当我把它包含进去时,我得到了上述错误信息。

c++ operator-overloading c++17 friend
1个回答
2
投票
ostream& NeuralNet::operator<<(ostream& os, NeuralNet& net){ ... }

需要被

ostream& operator<<(ostream& os, NeuralNet& net){

既然你说是 friend 函数,而不是成员函数。

© www.soinside.com 2019 - 2024. All rights reserved.