相当于Java的toString的C ++? [英] C++ equivalent of Java's toString?
本文介绍了相当于Java的toString的C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想控制自定义类对象写入流中的内容,即 cout
。在C ++中有可能吗?在Java中,出于类似的目的,您可以覆盖 toString()
方法。
I'd like to control what is written to a stream, i.e. cout
, for an object of a custom class. Is that possible in C++? In Java you could override the toString()
method for similar purpose.
推荐答案
在C ++中,您可以为 ostream
和您的自定义类重载 operator<<
$ b
In C++ you can overload operator<<
for ostream
and your custom class:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
这样,您可以在流上输出类的实例:
This way you can output instances of your class on streams:
A x = ...;
std::cout << x << std::endl;
如果您的操作员<<
想要打印出 A
类的内部并且确实需要访问其私有成员和受保护成员,您还可以将其声明为朋友函数:
In case your operator<<
wants to print out internals of class A
and really needs access to its private and protected members you could also declare it as a friend function:
class A {
private:
friend std::ostream& operator<<(std::ostream&, const A&);
int j;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.j << ")";
}
这篇关于相当于Java的toString的C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文