重载运算符<<在C ++中的类中 [英] overload operator<< within a class in c++

查看:100
本文介绍了重载运算符<<在C ++中的类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用结构的类,并且我想重载<<.该结构的运算符,但仅限于该类之内:

I have a class that uses a struct, and I want to overload the << operator for that struct, but only within the class:

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);
}

我只能在声明运算符时<<重载带有Friendly关键字,但是运算符在我的代码中到处都是重载,而不仅仅是在类中.我如何使<<只能在该类中使用my_struct运算符吗?

I can only compile when I declare the operator<< overload w/ the friend keyword, but then the operator is overloaded everywhere in my code, not just in the class. How do I overload the << operator for my_struct ONLY within the class?

我将要使用重载运算符来打印my_struct,该成员是My_Class的成员

I will want to use the overloaded operator to print a my_struct which IS a member of My_Class

推荐答案

如何使<<只能在该类中使用my_struct的运算符?

How do I overload the << operator for my_struct ONLY within the class?

定义为

static std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //...

namespace {
    std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //...
}

实现MyClass.cpp文件中的

.

in the .cpp file in which you implement MyClass.

编辑:如果您确实确实需要限制该类的范围,则只需在该类中将其定义为私有静态函数即可.它只会在该类及其子类的作用域中.但是,它将隐藏为不相关的类定义的所有其他自定义operator<<(同样,仅在类内部及其子类中),除非可以用ADL找到它们,或者它们已经是std::ostream的成员.

If you really, really need to scope on the class and nothing else, then define it as a private static function in said class. It will only be in scope in that class and it's subclasses. It will hide all other custom operator<<'s defined for unrelated classes, though (again, only inside the class, and it's subclasses), unless they can be found with ADL, or are members of std::ostream already.

这篇关于重载运算符&lt;&lt;在C ++中的类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆