簡體   English   中英

C++ 如何打印對象?

[英]C++ How do I print an object?

我創建了一個構造函數

Location(double xIn,double yIn,string placeIn,int timeIn)
: x(xIn),y(yIn) ...so on {

假設我想打印 Location home(x,y,place,time); 那在main()

我該怎么做? 我一直在四處尋找並被告知使用operator<< 我將如何實現這一點?

更新:在創建了一些 get 方法並且我嘗試這樣做之后,由於問題無法完全編譯它

ostream &operator<<(ostream & o, const Location & rhs){

        o << rhs.getX() << "," << rhs.getY() << "," << rhs.getPlace() << "," << rhs.getTime();
        return o; }

這是用於重載operator<<的模板:

class Any
{
  public:
    friend std::ostream& operator<<(std::ostream& output, const Any& a);
  private:
    int member;
};

std::ostream&
operator<<(std::ostream& output, const Any& a)
{
  output << a.member;
  return output;
}

這是一種可能的模板,還有其他的可能性。 在 Internet 上搜索“c++ 流插入運算符重載示例”以獲取其他實現。

暫無
暫無

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

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