簡體   English   中英

C ++運算符+ =重載

[英]C++ Operator += overload

我想重載運算符+ =,以便我將在使用它時使用a + = b; 它將在向量a中添加b到標頭中:

public:
...
void Book::operator+=(std::string a, std::vector<std::string>>b);
private:
...
    std::string b;
    stf::vector<std::string> a;

這是cpp中的實現

void Book::operator+=(std::string a, std::vector<std::string>>b)
{
b.push_back(a);
}

我的錯誤是什么? 對我來說還不清楚使用重載運算符

您可以使用成員函數或非成員函數重載+=運算符。

當它是成員函數時,運算符的LHS是將在其上調用該函數的對象,而運算符的RHS是該函數的參數。 因此,成員函數的唯一參數將是RHS。

就您而言,您有兩個參數。 因此,這是錯誤的。 您可以使用:

void operator+=(std::string a);
void operator+=(std::vector<std::string>>b);

或類似的情況,成員函數中只有一個參數。

順便說一句,您不需要使用void Book::operator+= ,只需使用void operator+=

另外,使用起來更慣用

Book& operator+=(std::string const& a);
Book& operator+=(std::vector<std::string>> const& b);

第一個的實現可能是:

Book& operator+=(std::string const& aNew)
{
   b.push_back(aNew);
   return *this;
}

第二個可能是:

Book& operator+=(std::vector<std::string>> const& bNew);
{
   b.insert(b.end(), bNew.begin(), bNew.end());
   return *this;
}

有關這些操作的詳細信息,請參見std :: vector文檔

PS不要將成員變量ab與同名的輸入參數混淆。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM