c++ - 显式复制构造函数编译错误

标签 c++ c++11 constructor

我在检查 C++ 中的运算符重载时遇到了一些我没有预料到的事情,对此我有一些疑问。

我的复制构造函数声明并实现为

explicit Vector(const Vector& v);

Vector::Vector(const Vector& v) :
_x(v._x), _y(v._y), _z(v._z) {}

然后我重载了复合赋值运算符

Vector Vector::operator+(const Vector& v) const
{
    Vector tmp(*this);
    tmp += v;
    return tmp;
}

Vector Vector::operator-(const Vector& v) const
{
    Vector tmp(*this);
    tmp -= v;
    return tmp;
}

但是,在 return 语句中,我收到一条错误消息,提示 no matching constructor for initialization of 'Vector'

因为我唯一添加到构造函数的是 explicit 关键字,所以我删除了它并且代码编译得很好,为什么?

我也在检查 C++11 的新内容,发现我可以像移动构造函数一样声明我的构造函数

explicit Vector(const Vector&& v);

并且代码编译得很好。如果这样做,我是否必须同时拥有复制和移动构造函数?

explicit Vector(const Vector& v);
explicit Vector(const Vector&& v);

或者仅仅使用移动构造函数就可以正常工作?如果我想坚持使用 C++11,应该遵循的正确方法是什么?

最佳答案

你定义了一个显式拷贝构造函数,但是函数

Vector Vector::operator+(const Vector& v) const

Vector Vector::operator-(const Vector& v) const

必须按值返回,并且不能再返回,因为 explicit(换句话说,它们不能将 tmp 复制到返回的对象中)。

I also was checking new stuff from C++11 and occurred that I can declare my constructor like a moving-constructor explicit Vector(const Vector&& v); and the code compiles just fine. If I do that, do I have to have both copy and move constructors?

不确定我是否理解您的意思。如果您只声明一个显式移动构造函数(这将阻止编译器生成默认复制构造函数),您将遇到同样的问题。我无法生成“可编译”代码。

关于c++ - 显式复制构造函数编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29472565/

相关文章:

c++ - 错误 : Storage class specifiers invalid for parameter declarations

c++ - `constexpr` 和 `const` 的区别

c++11 - C++ 11 uint类型与u_int

java - 抽象多态性和继承的类分配错误

c# - PInvoke "Attempted to read or write protected memory"

c++ - 计算具有不同行高的网格中的滚动条高度

c++ - 使用模板和右值引用的重载解决方案

java - 为什么实例字段的值变为空?

inheritance - 如何在 Qt Creator 中使用父类(super class)构造函数?

c++ - 'this' 指针错误