繁体   English   中英

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

[英]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。

为什么 ostream iomanip 在传递给 operator&lt; 时不需要模板参数<!--?</div--><div id="text_translate"><p> 在 gnu stdc++ header ostream 的命名空间 std 中,这是 std::endl 的定义:</p><pre> template&lt;typename _CharT, typename _Traits&gt; inline basic_ostream&lt;_CharT, _Traits&gt;&amp; endl(basic_ostream&lt;_CharT, _Traits&gt;&amp; __os) { return flush(__os.put(__os.widen('\n'))); }</pre><p> 为什么可以写std::cout &lt;&lt; std::endl; 在没有模板参数的情况下使用endl ?</p></div>

[英]Why does an ostream iomanip not need template parameters when passed to operator<<?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM