+= C++ 中的运算符,用于将作者添加到列表

+= operator in C++ to add Autors to list

我想知道如何使用 c++ 中的 += 运算符将项目添加到列表中;

在我的主要我有这样的东西:

  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 函数更改为 += 运算符以添加作者。这怎么可能?这样我就可以为任何出版物添加作者。我的出版物 class 与 :

有关

我的 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;
}

不会报错,但只会添加最后一位作者。我怎样才能实现将所有作者保留在 otherAuthors 中?

您可能应该使用引用,因为您将向量作为副本传递并且它不会影响其内容。 像这样尝试:

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;
}

您的实施问题:

如果您希望您的 operator+= 提供与内置运算符类似的行为,您必须采用类似的签名:您必须对引用进行操作,return 该引用:

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 节。顺便说一句,您可能对这些有用的东西感兴趣 rules and guidelines for operator overloading

使用您的签名,您首先复制向量来构造参数,然后您将更改此副本而不是原始副本。然后您将 return 更改向量的另一个副本,这不是复合赋值的正常行为。

您方法的其他问题:

我认为您的方法很危险,因为它不仅对作者列表中的作者超载 +=,而且对指向字符串的共享指针的任何向量超载。

可能这是你的意图。但如果不这样做,这也会产生意想不到的副作用并迅速失控。

还要考虑运算符的一致性。对于内置运算符,人们会期望 a += b 提供与 a = a + b 或 a = b + a(加法的交换性)相同的结果。当然你没有义务尊重这个意思,但是如果你的重载运算符的行为与这个原则有很大的不同,你应该问问自己这是否真的是个好主意。毕竟是only some syntactic sugar