簡體   English   中英

重載 Ostream 運算符

[英]Overloading Ostream operator

我發現當我在 class 或結構中創建 ostream 運算符時,它只接受一個參數,因為第二個參數是 This 指針,所以我嘗試這樣做,但它不起作用

PS 我知道我應該在 class 或結構之外創建它作為免費的 function 但我想了解為什么?

struct Vector2 
{
    float x,y ; 
    Vector2(float ax , float ay )
    {
        x = ax ; 
        y = ay ; 
    }
    std:: ostream&  operator<< (std::ostream&  stream )
    { 
        return stream <<this->x<< " , "<< this->y ; 
    }
}

<<被重載時, a << b意味着要么

operator<<(a,b)

如果過載是免費的 function,或

a.operator<<(b)

如果是會員。

也就是說,對於定義為成員的運算符,左邊的參數是*this ,你需要寫

Vector2 v;
v << std::cout;

相當於

Vector2 v;
v.operator<<(std::cout);

暫無
暫無

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

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