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

标签 c++ class operator-overloading encapsulation

你们中的许多人可能知道以下 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<<采用多个参数,它总是采用两个操作数,左操作数和右操作数。上例中的左操作数是 coutostream右操作数是 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 完全无关.你写的是 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;
    }
};

或者作为 friend :

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

关于c++ - 重载 << 运算符 - 多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17064297/

相关文章:

c++ - 图形用户界面设计帮助 - MFC

java - 即使类和构造函数存在,也无法实例化类型

c++ - C++ 运算符重载中的类型推断

c++ - 赋值运算符(字符串)右侧的类型是什么?

c++ - Gstreamer 元素在 C 程序中不可用,但使用 gst-tools 确实可用

c++ - 与 register 关键字相关的其他语义

c++ - 一个大文件,还是几个小文件?

php - 在php中从子类调用父类的函数

c# - 给类对象一个值c#

c++ - 运算符重载的基本规则和惯用法是什么?