运算符过载但不可行
Operator overload but not viable
我为 class 中的 class TextureImage 重载了 operator =,但编译器一直说没有可行的运算符“=”。
TextureImage& operator=(TextureImage i){
this->x = i.getX();
this->y = i.getY();
this->n = i.getN();
this->data = i.getData();
return *this;
}
如果我将 const
添加到函数中,编译器会说我无法在 const 成员函数中分配给非静态数据成员。
那么如何在这里重载运算符=
您当然不希望将赋值运算符重载为 const
成员函数。硬要的话,把所有的成员变量都设为mutable
.
规范形式看起来像
TextureImage& operator=(const TextureImage& i) {
x = i.x;
y = i.y;
n = i.n;
data = i.data;
return *this;
}
请注意,您不需要在那里使用吸气剂。
如果没有其他事情要做,您不需要实现自己的赋值运算符,因为编译器已经自动或按需生成该代码
TextureImage& operator=(const TextureImage& i) = default;
虽然我怀疑 data
需要一些更特殊的处理,因为它听起来是一种数组或指针成员变量。
在这种情况下,我建议您使用 std::array
或 std::vector
作为数据成员并坚持使用默认实现。
我为 class 中的 class TextureImage 重载了 operator =,但编译器一直说没有可行的运算符“=”。
TextureImage& operator=(TextureImage i){
this->x = i.getX();
this->y = i.getY();
this->n = i.getN();
this->data = i.getData();
return *this;
}
如果我将 const
添加到函数中,编译器会说我无法在 const 成员函数中分配给非静态数据成员。
那么如何在这里重载运算符=
您当然不希望将赋值运算符重载为 const
成员函数。硬要的话,把所有的成员变量都设为mutable
.
规范形式看起来像
TextureImage& operator=(const TextureImage& i) {
x = i.x;
y = i.y;
n = i.n;
data = i.data;
return *this;
}
请注意,您不需要在那里使用吸气剂。
如果没有其他事情要做,您不需要实现自己的赋值运算符,因为编译器已经自动或按需生成该代码
TextureImage& operator=(const TextureImage& i) = default;
虽然我怀疑 data
需要一些更特殊的处理,因为它听起来是一种数组或指针成员变量。
在这种情况下,我建议您使用 std::array
或 std::vector
作为数据成员并坚持使用默认实现。