C++ 我如何使用 cout << myclass
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2981836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use cout << myclass
提问by ali
myclass
is a C++ class written by me and when I write:
myclass
是我写的一个 C++ 类,当我写的时候:
myclass x;
cout << x;
How do I output 10
or 20.2
, like an integer
or a float
value?
我如何输出10
or 20.2
,比如一个integer
或一个float
值?
回答by Jerry Coffin
Typically by overloading operator<<
for your class:
通常通过operator<<
为您的类重载:
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;
}
回答by Rich Adams
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.
然后,当您执行此操作时cout << x
(您的情况中x
的类型myclass
为where ),它将输出您在方法中告诉它的任何内容。在上面的例子中,它将是x.somevalue
成员。
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.
如果成员的类型不能直接添加到 an ostream
,那么您还需要<<
使用与上述相同的方法重载该类型的运算符。
回答by Tristram Gr?bener
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)
您需要返回对 os 的引用以链接输出(cout << foo << 42 << endl)
回答by Emil Mocan
Alternative:
选择:
struct myclass {
int i;
inline operator int() const
{
return i;
}
};