在c ++中的类中重载operator <<

aar*_*acy 5 c++ operator-overloading

我有一个使用结构的类,我想重载该结构的<<运算符,但只在类中:

typedef struct my_struct_t {
  int a;
  char c;
} my_struct;

class My_Class
{
  public:
    My_Class();
    friend ostream& operator<< (ostream& os, my_struct m);
}
Run Code Online (Sandbox Code Playgroud)

我只能在我声明运算符<< overload w/friend关键字时编译,但随后运算符在我的代码中的所有地方都被重载,而不仅仅是在类中.如何在类中重载<< operator for my_struct?

编辑:我想使用重载运算符来打印my_struct,它是My_Class的成员

小智 10

不要使用operator <<.使用命名成员函数,并将其设为私有.

class My_Class
{
  public:
    My_Class();
 private:
    void Print( ostream & os, const my_struct & m );
};
Run Code Online (Sandbox Code Playgroud)

请注意,无论使用哪种方法,都应将结构作为const引用传递.

编辑:没有必要使操作符<<类的成员只是因此您​​可以使用它来打印类的成员.你可以使它成为结构的朋友,或者是一个完全自由的函数,然后由类使用.


Mar*_*utz 9

如何在类中重载<< operator for my_struct?

将其定义为

static std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //...
Run Code Online (Sandbox Code Playgroud)

要么

namespace {
    std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //...
}
Run Code Online (Sandbox Code Playgroud)

.cpp您实施的文件中MyClass.

编辑:如果你真的,真的需要在类上进行范围而不是其他任何东西,那么在所述类中将其定义为私有静态函数.它只会在该类的范围内,而且它是子类.它将隐藏operator<<为不相关的类定义的所有其他自定义(但同样,仅在类中,并且它是子类),除非它们可以在ADL中找到,或者std::ostream已经是成员.