运算符重载<< - 多个参数
Overloading << operator - multiple parameters
你们中的许多人可能知道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;
}
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 左角支架解释为操作员&lt;而不是模板参数
- 重载运算符<<:此运算符函数的参数太多
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多