C++运算符重载示例

huf*_*uff 1 c++ operator-overloading

好吧,我是操作员重载的新手,我发现了这个问题.我宁愿问你:D.而不是记录自己

关键是,我知道如何进行简单的运算符重载,但我遇到了堆栈运算符的问题.我将尝试举一个相对简单的例子:

struct dxfdat
{
 int a;
 string b;

 /* here is the question */
}

/* use: */
dxfdat example;

example << "lalala" << 483 << "puff" << 1029 << endl;
Run Code Online (Sandbox Code Playgroud)

"lalala" << 483 << "puff" << 1029 << endl应存储在b.

dxfdat& operator<< (T a)这样的事情可以使用一个参数(example << 7),但我希望它以一种cout方式工作.

抱歉这么懒.

编辑:

真实的......好吧,它有点棘手......实际上,b不是一个字符串,而是一个其他对象的矢量,example << "lalala" << 483 << "puff" << 1029 << endl应该只创建一个对象.

这就是我正在尝试(翻译),虽然我不知道如何告诉它何时创建对象(因为它从左到右,不是吗?):

struct dxfDato
{
    dxfDato(int c = 0, string v = 0, int t = 0) { cod = c; val= v; ty = t; }

    int ty;
    int cod;
    string val;
};

struct dxfItem
{
    int cl;
    string val;
    vector<dxfDato> dats;
    vector<dxfItem> sons;

    template <class T>
    dxfItem &operator<<(const T &t)
    {
        dxfDato dd;
        std::stringstream ss;
        ss << t;
        val = ss;
        dats.push_back(dd); // this way, it creates a lot of objects
        return d;
    }

};

dxfItem headers;

headers << "lalala" << 54789 << "sdfa" << 483 << endl;
// this should create *just one object* in dats vector,
// and put everything on string val
Run Code Online (Sandbox Code Playgroud)

谢谢你的一切,

注意:我必须提取并翻译很多东西才能把它放在这里,所以我没有检查代码中的愚蠢错误.

(很抱歉扩大这个问题,请告诉我,如果我误用了stackoverflow的问题系统)

Ale*_*ler 7

诀窍是从自己返回一个引用operator <<- 这样,操作符可以"堆叠".

class me {

    me& operator<<(int t) {...; return *this;}
};

me m;
m << 4 << 5 << 6;
Run Code Online (Sandbox Code Playgroud)

只需为您想要支持的所有类型的移位操作符重载(或者如果您能负担得起危险,则将其设为模板)!