[英]how to overload << operator in c++ to use repeatedly?
Sorry for the not clear title.抱歉标题不清楚。 Recently I started to learn C++ and I don't know how to overload operator <<
to make it repeatable.最近我开始学习 C++ 并且我不知道如何重载运算符<<
以使其可重复。
Here's an example code.这是一个示例代码。
class Foo{
private:
int* a;
int idx = 0;
public:
Foo(){a = new int[100];
void operator<< (int a) {arr[idx++] = a;}
What <<
does is basically class get integer number as an operand and save it into arr
.(Ignore overflow case here) <<
所做的基本上是 class 将 integer 编号作为操作数并将其保存到arr
中。(此处忽略溢出情况)
For example, a << 100
will add 100 into array.例如, a << 100
会将 100 添加到数组中。
What I want to do is make <<
operator can be repeatedly used inline like a << 100 << 200
How should I fix above code to allow this function?我想要做的是使<<
运算符可以像a << 100 << 200
一样内联重复使用我应该如何修复上面的代码以允许这个 function?
Thanks in advance:)提前致谢:)
The overloaded Foo::operator<<()
takes actually two arguments:重载的Foo::operator<<()
实际上需要两个 arguments:
int
given as right-hand side右边给出的参数int
this
from left-hand side.左侧的隐含this
。 To allow chaining of this operator, it should return a reference to the left-hand-side (ie *this
) to become usable at left-hand-side itself.为了允许链接此运算符,它应该返回对左侧的引用(即*this
)以在左侧本身可用。
Sample code:示例代码:
#include <iostream>
struct Foo {
Foo& operator<<(int a)
{
std::cout << ' ' << a;
return *this;
}
};
int main()
{
Foo foo;
foo << 1 << 2 << 3;
}
Output: Output:
1 2 3
Chaining is enabled by returning a reference to the instance so you can call another method:通过返回对实例的引用来启用链接,因此您可以调用另一个方法:
class Foo{
private:
std::vector<int> a;
public:
Foo(){}
Foo& operator<< (int a) {
arr.push_back(a);
return *this;
}
};
Now you can call f << 100 << 200 << 42;
现在你可以调用f << 100 << 200 << 42;
. .
Note that I replaced the array with a std::vector
to make Foo
less broken (unless you have a descrutor that you did not show it was leaking memory, you could fix that, but then still copying would cause problems, in short you need to respect the rule of 3/5 when you own a resource, using a std::vector
makes things much simpler).请注意,我用std::vector
替换了数组以减少Foo
损坏(除非您有一个描述符,您没有显示它正在泄漏 memory,您可以修复它,但仍然复制会导致问题,总之您需要当您拥有资源时要遵守 3/5 规则,使用std::vector
会使事情变得更简单)。
PS: Same works for other methods. PS:其他方法也一样。 You simply call another method on the returned reference to this
.您只需在返回的this
引用上调用另一个方法。 Note that operators are just methods (with some syntactic sugar) and to see that you can write as well f.operator<<(100).operator<<(200).operator<<(42);
请注意,运算符只是方法(带有一些语法糖),并且可以看到您也可以编写f.operator<<(100).operator<<(200).operator<<(42);
. .
Return a reference to *this
.返回对*this
的引用。 It's unrelated but you should use a vector to avoid memory leaks.这是不相关的,但您应该使用向量来避免 memory 泄漏。 Try to avoid raw new
尽量避免生new
class Foo{
private:
std::vector<int> a;
public:
Foo &operator<< (int a) {
arr.push_back(a);
return *this;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.