一、重载原则
- 赋值运算符的重载,用于在用户自定义的类型对象之间的彼此赋值;
- 算术运算符的重载,用于给数字类型增加算术属性;
- 关系运算符的重载,前提是类对象可进行逻辑比较;
- 重载算术和逻辑运算符时,注意满足交换性;
- “[ ]”的重载,用于检索容器类元素;
- “<<”和“>>”的重载,用于从I/O流中读写对象;
- “->”的重载,用于实现所谓的“智能指针(smart pointers)”;
- new、delete较少重载;
- 其他不得重载。
二、基本框架
- 重载赋值运算符
Test& Test::operator=(const Test& t)
{
if(&t != this){ ... }
return *this;
}- 原因:解决类中包含指针的问题,避免析构时出错。
- 重载赋值运算符函数除了完成赋值操作外,还返回对被赋值对象的引用
- 注意同拷贝构造函数的区别:若 被赋值对象不存在,则调用拷贝构造函数;否则调用赋值函数。
- 重载二元运算符
//成员运算符函数
declare:
Date operator+(int) const;
defination:
Date Date::operator+(int n) const
{
....
return *this;
}
//非成员运算符函数
declare:
friend Date operator+(int, const Date&);
defination:
Date Date::operator+(int n, const Date& dt)
{
Date* d = new Date();
....
return *d;
} - 重载一元运算符
- 重载“->” 运算符
template<class T>
class CountedPtr
{
public:
//initialize pointer with existing pointer
explicit CountedPtr(T* p = 0)
: ptr(p), count(new long(1)) {}
//copy pointer(one more owner)
CountedPtr(const CountedPtr<T>& p) throw()
: ptr(p.ptr),count(p.count) {}
//delete value if this was the last owner
~CountedPtr() throw()
{
dispose();
}
//assignment
CountedPtr<T>& operator=(const CountedPtr<T>& p) throw()
{
if(this != &p)
{
dispose();
ptr = p.ptr;
count = p.count;
++*count;
}
return *this;
}
//acess the value to which the pointer refers
T& operator*() const throw()
{
return *ptr;
}
T* operator->() const throw()
{
return ptr;
}
private:
void dispose()
{
if(--*count == 0)
{
delete count;
delete ptr;
}
}
private:
T* ptr;
long* count;
}; - 重载
1万+




被折叠的 条评论
为什么被折叠?



