How can I use cout << myclass

2020-01-23 03:22发布

myclass is a C++ class written by me and when I write:

myclass x;
cout << x;

How do I output 10 or 20.2, like an integer or a float value?

4条回答
时光不老,我们不散
2楼-- · 2020-01-23 03:53

Alternative:

struct myclass { 
    int i;
    inline operator int() const 
    {
        return i; 
    }
};
查看更多
何必那么认真
3楼-- · 2020-01-23 03:55

Typically by overloading operator<< for your class:

struct myclass { 
    int i;
};

std::ostream &operator<<(std::ostream &os, myclass const &m) { 
    return os << m.i;
}

int main() { 
    myclass x(10);

    std::cout << x;
    return 0;
}
查看更多
倾城 Initia
4楼-- · 2020-01-23 03:55

You need to overload the << operator,

std::ostream& operator<<(std::ostream& os, const myclass& obj)
{
      os << obj.somevalue;
      return os;
}

Then when you do cout << x (where x is of type myclass in your case), it would output whatever you've told it to in the method. In the case of the example above it would be the x.somevalue member.

If the type of the member can't be added directly to an ostream, then you would need to overload the << operator for that type also, using the same method as above.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-01-23 04:17

it's very easy, just implement :

std::ostream & operator<<(std::ostream & os, const myclass & foo)
{
   os << foo.var;
   return os;
}

You need to return a reference to os in order to chain the outpout (cout << foo << 42 << endl)

查看更多
登录 后发表回答