簡體   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