[英]how to overload << operator in c++ to use repeatedly?
抱歉標題不清楚。 最近我開始學習 C++ 並且我不知道如何重載運算符<<
以使其可重復。
這是一個示例代碼。
class Foo{
private:
int* a;
int idx = 0;
public:
Foo(){a = new int[100];
void operator<< (int a) {arr[idx++] = a;}
<<
所做的基本上是 class 將 integer 編號作為操作數並將其保存到arr
中。(此處忽略溢出情況)
例如, a << 100
會將 100 添加到數組中。
我想要做的是使<<
運算符可以像a << 100 << 200
一樣內聯重復使用我應該如何修復上面的代碼以允許這個 function?
提前致謝:)
重載的Foo::operator<<()
實際上需要兩個 arguments:
int
this
。 為了允許鏈接此運算符,它應該返回對左側的引用(即*this
)以在左側本身可用。
示例代碼:
#include <iostream>
struct Foo {
Foo& operator<<(int a)
{
std::cout << ' ' << a;
return *this;
}
};
int main()
{
Foo foo;
foo << 1 << 2 << 3;
}
Output:
1 2 3
通過返回對實例的引用來啟用鏈接,因此您可以調用另一個方法:
class Foo{
private:
std::vector<int> a;
public:
Foo(){}
Foo& operator<< (int a) {
arr.push_back(a);
return *this;
}
};
現在你可以調用f << 100 << 200 << 42;
.
請注意,我用std::vector
替換了數組以減少Foo
損壞(除非您有一個描述符,您沒有顯示它正在泄漏 memory,您可以修復它,但仍然復制會導致問題,總之您需要當您擁有資源時要遵守 3/5 規則,使用std::vector
會使事情變得更簡單)。
PS:其他方法也一樣。 您只需在返回的this
引用上調用另一個方法。 請注意,運算符只是方法(帶有一些語法糖),並且可以看到您也可以編寫f.operator<<(100).operator<<(200).operator<<(42);
.
返回對*this
的引用。 這是不相關的,但您應該使用向量來避免 memory 泄漏。 盡量避免生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.