你们中的许多人可能知道以下 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
完全无关.你写的是 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/