初始化时强制使用赋值运算符,而不是复制构造函数

Enforce assignment operator instead of copy constructor on initialization?

本文关键字:复制 构造函数 赋值运算符 初始化      更新时间:2023-10-16

我正在C++中组装我自己的(愚蠢的)Scalars/List/Hash(类似perl..)东西。

我遇到了一个问题,必须将Scalar取消引用到List中,并且在初始化时尝试它不起作用。

List几个默认构造函数,其中5个在List()List(Scalar, Scalar, Scalar, Scalar)之间。

List stuff(1, 2, 3);
Scalar aref = stuff; // List overloads the (Scalar) cast operator
// the following line is the unwanted thing..
List failist = aref; // uses List::List(Scalar), so same as `List failist(aref);`
// however, these work
List thisworks;
thisworks = aref;
thisworks.operator=(aref);

列表标题:

class List : public Thing {
    std::vector<Scalar> stuff;
public:
    List();
    List(Scalar s1); // this gets called because initialization
    List(Scalar s1, Scalar s2);
    List(Scalar s1, Scalar s2, Scalar s3);
    List(Scalar s1, Scalar s2, Scalar s3, Scalar s4);
    List &operator=(const Scalar &other); // but i want this
    /* some getters/setters cut away */
    operator Scalar();
};

我真的很想用List mylist = listreference;,怎么办?

我想知道,如果您不希望List myList = scalar调用构造函数,那么为什么首先要使用它?

无论如何,将其明确为:

explicit List(Scalar s1);. 

这样,您就可以让编译器在以下行中吐出错误:

List myList = scalar; //error 

然后你将有机会纠正自己,要么写:

List myList(scalar); //ok

或者,

List myList; 
myList = scalar; //ok

请注意,您不能使List myList = scalar调用List& operator=(Scalar const&),但是您可以根据另一个函数来实现一个,或者根据一些常见的init函数来实现两者,以避免代码重复。后一种方法更好。

你不能这么做。List mylist = listreference;的意思是:用复制构造函数创建List类型的mylist对象。所以你有两个选择:

  1. 通过opeartor实现复制构造函数=
  2. 使用两行代码:List mylist = listreference; mylist = listreference;