C++ 过载ostream<&书信电报;操作人员

C++ 过载ostream<&书信电报;操作人员,c++,C++,我想知道是否可以重载,这里是重载提取和插入运算符的一个示例: /* 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 t

我想知道是否可以重载
,这里是重载提取和插入运算符的一个示例:

/*
    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;
}
/*
运算符:>x>>逗号>>y>>par2;
//检查是否有任何输入
如果(!is)返回为;
//检查有效的输入格式
if(par1!='('| |逗号!=','| | par2!=')){
//设置failbit以指示无效的输入格式
is.clear(ios_base::failbit);
回报是;
}
//为第二个参数指定输入值
对象名称=类名称(x,y);
回报是;
}

您可以使用上面的示例并修改格式以匹配所需的结果。

当其他人回答了如何重载
运算符IRC时,它是可重载的。。。因此,您想要做的可能是=)标准使用多种方式打印相同的数据。哈哈,我正在尝试一种方法,因为我不知道如何更改函数的参数,因为它们几乎相同,只是执行不同:(这将是一个插入运算符。此外,我认为这不能回答如何以两种方式打印对象。此运算符“插入”提取操作符通常与
cin
一起使用,它应该返回
ostream&
而不是void,但是如果我想添加另一个以不同方式打印的重载,该怎么办?例如:X=Y=然后返回一个ostream&对该ostream的引用,正如@Alejandro Diaz所建议的。N请注意,我的代码片段更像是一个指导,而不是您实际需要的。这是我所有代码中最直接的一行。它只是一个if语句,作为您代码的占位符。这类似于STL的一些流操纵器的实现方式。它们中的大多数是作为普通函数和pas实现的sed与接受函数指针作为输入的流操作符一样。但是对于具有自己输入参数的操纵器(如
std::setw()
),它们返回临时对象,这些临时对象记住输入值,并具有重载流运算符以知道要操作哪些流。与上面的示例不同,尽管使用
struct
初始化要比STL初始化简单得多。不过,这一概念相同。
void operator<<(ostream str, YourClass cls) {
    // generate required output
}
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 << "[ ]";}
if (show_it)
    std::cout << showdomino{d} << '\n';
else
    std::cout << hidedomino{} << '\n';