c++类的操作符重载注意事项

=重载 class& operator=(const class&)

一定要在operator = 中检查是否self assignment 对象的自我赋值
1.先清空现有的成员(释放当前内存空间)
2.传递拷贝进来的成员
3.return *this
4.可以考虑是否加入转移赋值class& operator=( class&&);

<<重载

friend ostream& operator<<(ostream &os, const classA &a);
如要打印private成员在类内声明为友元函数(最前面加friend)
最好不打印换行符等格式控制,只负责输出内容。

[]重载

最好同时定义常量与非常量版本,当作用于一个常量对象时,下标运算符返回常量引用以确保我们不会给返回的对象赋值。

type& operator[](int index){return element[index];}
const type& operator[](int index) const {return element[index];} 

运算操作符

算术(+,-)和关系(==)运算符一般定义为非成员函数,以允许左右侧对象转换。
他们一般不改变对象,以常引用传递。

猜你喜欢

转载自blog.csdn.net/shayne000/article/details/88566907