2

多くの人は、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;
}
4

2 に答える 2

2

簡単に言えば、オペレーターはTestインスタンスを返す必要があります。

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

Test& operator<<(Test& test, int val)
{
    test.data += val;
    return test;
}
于 2013-06-12T11:37:00.193 に答える