I was checking operator overloading in C++ and came across something I did not expect and have some doubts about it.
My copy constructor is declared and implemented as as
explicit Vector(const Vector& v);
Vector::Vector(const Vector& v) :
_x(v._x), _y(v._y), _z(v._z) {}
then I am overloading the compound assignment operators
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;
}
however, in the return
statements I got an error saying no matching constructor for initialization of 'Vector'
.
Since the only thing I added to my constructor was the explicit
keyword, I deleted it and the code compiles just fine, why?
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?
explicit Vector(const Vector& v);
explicit Vector(const Vector&& v);
or just having the move constructor will work fine? If I want to stick to C++11, what is the correct approach to follow?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…