簡體   English   中英

如何在 cout 中打印 object 值?

[英]How do I print an object value inside a cout?

我有一個名為obj1的 object ,並且我已經使用obj1 object 訪問了一個 class New實例(比如id )。 例如, obj1.id=500

然后我想打印出這條語句: "The name of id=500 is:" ,那么如何在cout語句中寫入obj1.id的值。

簡單來說 output id ,因為它是一個內置類型(int),你只需將消息的每個部分鏈接在一起,如下所示:

int main() {
    std::cout << "The name of id=" << obj1.id << " is:";
    return 0;
}

但是如果你還想output原始變量名,你必須使用預處理器宏(參見維基詞典字符串化)

// This can be used to generate a string from a variable name
#define NAME_OF_VARIABLE(var) #var

int main() {
    // Prints: "The name of id=500 is: obj1"
    std::cout << "The name of id=" << obj1.id << " is:" << NAME_OF_VARIABLE(obj1);
    return 0;
}

ostream& operator<<(ostream& osObject, const ObjecyType& obj) { osObject << "id= " << obj.getId() << "; return osObject; }

暫無
暫無

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

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