如何定义静态运算符<<? [英] How to define a static operator<<?

查看:231
本文介绍了如何定义静态运算符<<?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以定义一个只对类的静态成员操作的静态插入运算符?类似:

Is it possible to define a static insertion operator which operates on the static members of a class only? Something like:

class MyClass
{
public:
    static std::string msg;

    static MyClass& operator<< (const std::string& token) {
        msg.append(token);
        return *this;   // error, static
    }
};

或者:

static MyClass& operator<< (MyClass&, const std::string &token)
{
    MyClass::msg.append(token);
    return ?;
}

这是我要使用的方式:

MyClass << "message1" << "message2";

谢谢!

推荐答案

如果 MyClass 的所有成员都是静态的,那么可以返回一个新的实例。

If all the members of MyClass are static, it's possible to return a fresh instance.

但是,返回引用会带来问题。有两种解决方案:

However, returning a reference poses a problem. There are two solutions:


  • 定义静态实例

  • 通过复制而不是引用。

第二种方法是最简单的:

The second approach is easiest:

static MyClass operator<< (MyClass, const std::string &token)
{
     MyClass::msg.append(token);
     return MyClass();
}

第一行是多行:

static MyClass& operator<< (MyClass&, const std::string &token)
{
     static MyClass instance;

     MyClass::msg.append(token);
     return instance;
}

用法非常接近你想要的:

Usage is very close to what you want:

MyClass() << "message1" << "message2";






但是,请执行此操作。为什么不只是使用 std :: ostringstream ?你会得到格式化和一些更多的免费。如果您真的需要全局访问,请声明一个全局变量。


However, I would not recommend to do this. Why don't you just just use a std::ostringstream? You'll get formatting and some more for free. If you really need global access, declare a global variable.

这篇关于如何定义静态运算符&lt;&lt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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