练习复制构造函数和运算符重载
Practice Copy Constructor and Operator Overloading
我一直在练习创建复制构造函数和重载运算符,所以我想知道是否有人可以检查我的实现是否正确。这只是一个武断的实践例子。
class Rectangle
{
private:
int length;
int width;
public:
Rectangle(int len = 0, int w = 0)
{
length = len;
width = w;
}
Rectangle(const Rectangle &);
Rectangle operator + (const Rectangle &);
Rectangle operator = (const Rectangle &);
};
Rectangle::Rectangle(const Rectangle &right)
{
length = right.length;
width = right.width;
cout << "copy constructor" << endl;
}
Rectangle Rectangle::operator + (const Rectangle &right)
{
Rectangle temp;
temp.length = length + right.length + 1;
temp.width = width + right.width + 1;
cout << "+ operator" << endl;
return temp;
}
Rectangle Rectangle::operator = (const Rectangle &right)
{
Rectangle temp;
temp.length = right.length + 2;
temp.width = right.width + 2;
cout << "= operator" << endl;
return temp;
}
您的复制赋值操作符应该返回对自身的引用,并执行赋值:
Rectangle& Rectangle::operator= (const Rectangle &right)
{
length = right.length;
width = right.width;
cout << "= operator" << endl;
return *this;
}
对于:
Rectangle(int len = 0, int w = 0)
我建议将其显式化,以防止整数的隐式转换。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板