[英]Stringstream - Convert an object to a string
I have a complex object that I want to be able to pass into a std::ostringstream
with the <<
operator just like a string or int. 我有一个复杂的对象,希望能够通过
<<
运算符传递到std::ostringstream
,就像字符串或int一样。 I want to give the ostringstream the object's unique id (int) and/or name (string). 我想给ostringstream对象的唯一ID(整数)和/或名称(字符串)。 Is there an operator or method I can implement in my class to allow this to work?
我可以在我的课程中实现一个运算符或方法来使其工作吗?
Define an operator overload in the same namespace as your class: 在与您的类相同的名称空间中定义运算符重载:
template<typename charT, typename traits>
std::basic_ostream<charT, traits> &
operator<< (std::basic_ostream<charT, traits> &lhs, Your_class const &rhs) {
return lhs << rhs.id() << ' ' << rhs.name();
}
If the output function needs access to private members of your class then you can define it as a friend function: 如果输出函数需要访问类的私有成员,则可以将其定义为朋友函数:
class Your_class {
int id;
string name;
template<typename charT, typename traits>
friend std::basic_ostream<charT, traits> &
operator<< (std::basic_ostream<charT, traits> &lhs, Your_class const &rhs) {
return lhs << rhs.id << ' ' << rhs.name;
}
};
Note that this does not result in a member function, it's just a convenient way to declare and define a friend function at once. 请注意,这不会产生成员函数,这只是一次方便地声明和定义一个朋友函数的简便方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.