Vector(const Vector& other) // Copy constructor
{
x = other.x;
y = other.y;
Run Code Online (Sandbox Code Playgroud)
为什么参数是const?
Jer*_*fin 57
你已经得到了答案,提到确保ctor不能改变被复制的东西 - 而且他们是正确的,把const放在那里确实有这种效果.
但更重要的是,临时对象无法绑定到非const引用.复制文件必须引用const对象才能复制临时对象.
Nav*_*een 20
因为你不打算修改other
copy ctor中的参数,因为它是const.
当你这样做时x = other.x
,基本上意味着this->x = other.x
.所以你this
只是通过复制other
变量中的值来修改对象.由于other
变量在这里是只读的,因此它作为const-ref传递.