初始化时强制使用赋值运算符,而不是复制构造函数
Enforce assignment operator instead of copy constructor on initialization?
我正在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对象。所以你有两个选择:
- 通过opeartor实现复制构造函数=
- 使用两行代码:
List mylist = listreference; mylist = listreference;
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 复制构造函数、赋值运算符C++
- std::ofstream 作为类成员删除复制构造函数?
- 复制构造函数C++无法正确复制指针
- 关于复制构造函数的一个棘手问题
- 为什么调用复制构造函数而不是移动构造函数?
- 填充上编译器生成的复制构造函数之间的不一致
- C++ 对象指针数组的复制构造函数
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 防止在复制构造函数中隐式调用基构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 具有已删除移动和复制构造函数的类的就地构造
- 复制构造函数隐式转换问题
- 复制构造函数中的递归调用