运算符重载<< - 多个参数

Overloading << operator - multiple parameters

本文关键字:lt 参数 运算符 重载      更新时间:2023-10-16

你们中的许多人可能知道c++中的以下内容:

cout << 1 << 2 << 3 << 4; // would produce 1234

我正在尝试重新创建相同的东西-而是将其封装到一个类中,并将值递增为整数变量。

我得到错误:

错误:'int operator<<(const int&, const int&)'必须有类或枚举类型的参数|

class Test
{
private:
    int data;
public:
    Test() { data = 0; }
    void print() { cout << data; }
    friend int operator<<(const int &x, const int &y)
    {
        data += x;
        data += y;
    }
};
int main()
{
    Test a;
    a << 50 << 20;
    a.print();   //if I had only 1 parameter - it worked and printed out only 50
    return 0;
}

cout << 1 << 2 << 3 << 4;

的工作方式是一系列带有两个参数的调用,例如

(((cout << 1) << 2) << 3) << 4;

大致相当于:

cout << 1;
cout << 2;
cout << 3;
cout << 4;

所以你不写一个有多个参数的operator<<,它总是有两个操作数,左操作数和右操作数。在上面的例子中,左操作数是cout,即ostream,右操作数是向其写入的int。操作符返回左操作数,允许在下一个操作中再次使用它,依此类推,只要您链接在一起,就可以执行许多<<操作。

因此,cout << 1再次返回cout,因此(cout << 1) << 2调用操作符将1写入流并返回该流,然后在返回值上再次调用操作符将2写入流并再次返回该流。

这是无稽之谈:

friend int operator<<(const int &x, const int &y)
{
    data += x;
    data += y;
}

data应该来自哪里?友元函数不是类的成员,所以没有this指针,所以没有this->data,你也声称返回int,但不返回任何东西,这个类与Test完全无关。你写的是两个int型的operator<<,也就是说,为了做1 << 2,但这个操作符已经存在了,它是位移操作符,你不能重载它为内置类型,如int

你想:

class Test
{
private:
    int data;
public:
    Test() { data = 0; }
    void print() { cout << data; }
    Test& operator<<(int y)
    {
        data += x;
        return *this;
    }
};

或者作为朋友:

class Test
{
private:
    int data;
public:
    Test() { data = 0; }
    void print() { cout << data; }
    friend Test& operator<<(Test& t, int y)
    {
        t.data += x;
        return t;
    }
};

简而言之,操作符需要返回Test实例:

class Test
{
    ...
    friend Test& operator<<(Test& test, int val);
};
Test& operator<<(Test& test, int val)
{
    test.data += val;
    return test;
}