2015-08-15 16 views
1

我在想如何通過在C++中使用+ =運算符來將項目添加到列表中;+ =在C++中的運算符添加Autors到列表

在我主我有這樣的事情:

Bibliography herbspubs("Herb Sutter"); 
    std::shared_ptr<Paper> king = std::make_shared<Paper>("The return of the King", 2009, "Dr. Dobbs journal", 1.56f); 
    king->addAuthor(std::make_shared<std::string>("Joe Walsh")); 

但addAuthor功能我想更改爲+ =運算符添加作者。這怎麼可能?這樣我就可以將作者添加到任何出版物。

  • Papper
  • 會議

我publication.h樣子:

#ifndef PUBLICATIONS_H 
#define PUBLICATIONS_H 

#include <string> 
#include <vector> 
#include <memory> 

typedef std::vector<std::shared_ptr<std::string>> otherAuthors; 
class Publications 
    { 
    public: 
    explicit Publications(std::string orderTitle, int aYear, std::string aPublisher); 

    private: 

    std::vector<std::shared_ptr<std::string>> otherAuthors; 
    }; 


std::vector<std::shared_ptr<std::string>> operator +=(std::vector<std::shared_ptr<std::string>> otherAuthors,const std::shared_ptr<std::string> newAuthor); 

#endif // PUBLICATIONS_H 

Publication.cpp

我的出版類與連接
void Publications::addAuthor(const std::shared_ptr<std::string> newAuthor) 
{ 
    otherAuthors+=newAuthor; 
    //otherAuthors.push_back(newAuthor); 

} 

std::vector<std::shared_ptr<std::string>> operator +=(std::vector<std::shared_ptr<std::string>> otherAuthors,const std::shared_ptr<std::string> newAuthor){ 
    otherAuthors.push_back(newAuthor); 
    return otherAuthors; 
} 

不會出現錯誤,但只會添加最後一位作者。我如何實現它將所有作者保存在其他作者中?

+0

https://msdn.microsoft.com/en-us/library/5tk49fh2.aspx – Pradheep

+0

您按值傳遞並返回矢量,所以只有副本會受到影響。更改爲使用參考。 –

回答

0

您應該使用引用,因爲您將向量作爲副本傳遞,並且不影響其內容。 嘗試這樣的:

std::vector<std::shared_ptr<std::string>> operator +=(std::vector<std::shared_ptr<std::string>> &otherAuthors,const std::shared_ptr<std::string> newAuthor){ 
    otherAuthors.push_back(newAuthor); 
    return otherAuthors; 
} 
0

的問題與您實現:

如果你希望你的運營商+ =提供比同類的行爲內置的運營商,你必須採取類似的簽名:你必須參考並返回該參考文獻:

std::vector<std::shared_ptr<std::string>> & operator+= (std::vector<std::shared_ptr<std::string>> & otherAuthors, const std::shared_ptr<std::string> newAuthor) { 
    otherAuthors.push_back(newAuthor); 
    return otherAuthors; 
} 

另請參閱標準的第13.6/18節。順便提一下,您可能對這些有用的rulesguidelines for operator overloading感興趣。

隨着你的簽名,你首先製作一個向量的副本來構造參數,然後你會改變這個副本而不是原來的。然後,您將返回變化向量的另一個副本,這不是複合賦值的正常行爲。

其他問題與你的方法:

我覺得你的做法是危險的,因爲它不僅是在作者名單的作者,但共享指針爲字符串任何載體重載+=

可能是你的意圖。但是,如果沒有,這也可能會產生意想不到的副作用,並很快失去控制。

也想想運營商的一致性。對於內置運算符,可以預期a += b提供與a = a + b或a = b + a(加法的交換性)相同的結果。當然,你沒有義務去尊重這個意思,但是如果你的重載操作符的行爲與這個原則有很大的不同,你應該問自己這是否是一個非常好的主意。畢竟,這是only some syntactic sugar