簡體   English   中英

運算符重載<<錯誤

[英]Operator overloading << error

我收到編譯器錯誤

no match for 'operator<<' in 'std::cout << VertexPriority(2, 4u)' 

在引用此運算符重載的主類中,但是我無法理解錯誤的位置。

這里有運算符重載線,我在類定義中實現了它。

std::ostream& operator<<(std::ostream& out) const { return out << "Vertex: " << this->vertex << ", Priority: " << this->priority; }

頂點和優先級是整數和無符號整數。

在主類中,我試圖這樣做:

std::cout << VertexPriority(2, 3) << std::endl;

像這樣定義它:

class VertexPriority {
    ...

    friend std::ostream& operator<< (std::ostream& out, const VertexPriority& vp);
};

std::ostream& operator<< (std::ostream& out, const VertexPriority& vp) {
    return out << "Vertex: " << vp.vertex << ", Priority: " << vp.priority;
}

如果VertexPriority::vertexVertexPriority::priority不公開,則必須使用friend關鍵字。

如需更多幫助,請閱讀本教程: http : //www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM