[英]Overload ostream << operator
I was wondering if it is possible to overload the << operator
in the need for printing an object in the class in two certain way. 我想知道是否有可能以两种特定方式重载
<< operator
,以在类中打印对象。
For example, I'm building a domino game so I need to print my cubes with the numbers : [1][6][6][3]
And print the computers cubes : [ ][ ]
例如,我正在构建一个多米诺骨牌游戏,因此我需要使用以下数字打印我的多维数据集:
[1][6][6][3]
并打印计算机多维数据集: [ ][ ]
Here is one example of overloaded extraction and insertion operators: 这是重载提取和插入运算符的一个示例:
/*
Operator: <<
This insertion operator outputs the data members of
class object instantiation in the format:(x,y)
The returning type ostream&, allows
you to chain more then one objects to be printed.
*/
ostream& operator<< (ostream& os, class_name& object_name) {
return os << '(' << object_name.get_data_memberx()
<< ',' << object_name.get_data_membery()
<< ')';
}
/*
Operator: >>
This extraction operator creates an input stream it
inserts to it values for of all the data members of
the class passed by reference and returns it.
Input format: (x,y)
*/
istream& operator>> (istream& is, class_name& object_name) {
char par1, comma, par2;
double x, y;
is >> par1 >> x >> comma >> y >> par2;
// check if any input
if(!is) return is;
// check for valid input format
if (par1 != '(' || comma != ',' || par2 != ')') {
// set failbit to indicate invalid input format
is.clear(ios_base::failbit);
return is;
}
// assign input values to second argument
object_name = class_name(x,y);
return is;
}
You could use the above example and modify the formats to match the desired result. 您可以使用上面的示例并修改格式以匹配所需的结果。
While the others have answered how to overload operator<<
, it's not clear how to have two different formats. 虽然其他人已经回答了如何重载
operator<<
,但是还不清楚如何具有两种不同的格式。 I recommend this: temporary objects. 我建议这样做:临时对象。
struct showdomino {
domino& d;
};
std::ostream& operator<<(std::ostream& out, showdomino dom)
{return out << '[' << dom->d.number << ']';}
struct hidedomino {};
std::ostream& operator<<(std::ostream& out, hidedomino dom)
{return out << "[ ]";}
Then usage is vaguely like this: 然后用法大概是这样的:
if (show_it)
std::cout << showdomino{d} << '\n';
else
std::cout << hidedomino{} << '\n';
The << operator used for cout is actually the bitwise left shift operator that is overloaded to obtain this behaviour. 用于cout的<<运算符实际上是按位左移运算符,该运算符被重载以获得此行为。
I don't really understand what you want to achieve exactly (a code snippet would have been helpful). 我不太了解您要实现的目标(代码段会有所帮助)。 But, it seems you want to overload << for an ostream and a YourClass type.
但是,似乎您想为一个ostream和YourClass类型重载<<。 You can have something like:
您可以有类似以下内容:
void operator<<(ostream str, YourClass cls) {
// generate required output
}
Note that this acts as a regular function, just the calling syntax is different. 请注意,这是一个常规函数,只是调用语法不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.