我在想如何通過在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;
}
不會出現錯誤,但只會添加最後一位作者。我如何實現它將所有作者保存在其他作者中?
https://msdn.microsoft.com/en-us/library/5tk49fh2.aspx – Pradheep
您按值傳遞並返回矢量,所以只有副本會受到影響。更改爲使用參考。 –