对=的重载(实现深拷贝)
例1
class point;
class Array
{
private:
point *p;
int size;
public:
Array(Array &a)
{
size = a.size;
p = new point[size];
for(int i = 0;i < size;i++)
p[i] = a.p[i];
}//拷贝复制函数,少了这个会出问题
Array(int n, point pp)
{
size = n;
p = new point[size];
for(int i = 0;i < size;i++)
p[i] = pp;//经过实践,发现这一步是将point类的数据导入到Array类
//之前做的时候没有把pp赋给p[i],最后结果输出要么是0要么是不规则数
}
~Array(){}
Array &operator=(Array&a)
{
if(&a != this)
{
if(size != a.size)
{
delete[] p;
size = a.size;
p = new point[size];
}
for(int i = 0;i < size;i++)
p[i] = a.p[i];
//开辟新空间,深拷贝,把a的p数组传给this
}
return *this;
}
};
例2
//对string类的重写
class mystr
{
private:
char *str;
int size;
public:
mystr& operator=(mystr &ss)
{
if(this == &ss) return *this;
if(str != NULL)
{
delete[] str;//清空原来的内容
str = NULL;
}
size = strlen(SS);
str = new char[size+1];
strcpy(str,ss);
return *this;
}
}
对+=的重载
class mystr
{
private:
char *str;
int size;
public:
mystr &operator+=(mystr &ss)
{
size += ss.size;
strcat(str,ss.str);
return *this;
/*错误示范
mystr s1;
s1.size = size + ss.size;
s1.str = new char[size+1];
s1.str = strcat(str,ss.str);
return s1;
*/
//这种方式在win32下会显示乱码,在Linux下会提示被释放两次,并且不输出字符,无需再申请一个临时变量储存数据
}
}
对+的重载
class mystr
{
private:
char *str;
int size;
public:
mystr &operator+(mystr &ss)
{
size += ss.size;
strcat(str,ss.str);
return *this;
/*
mystr s1;
s1.size = size + ss.size;
s1.str = new char[s1.size+1];
s1.str = strcat(str,ss.str);
return s1;
*/
//仍然是错误示范,同上
}
mystr &operator+(char *ss)
{
size += strlen(ss);
strcat(str,ss);
return *this;
//错误示范和上一个函数的类似
}
}
对<<和>>重载
class mystr
{
private:
char *str;
public:
friend ostream& operator<<(ostream &os,mystr &ss)
{
os << ss.str << endl;
return os;
//这样直接输出ss里面的字符串和换行符
}
friend istream& operator>>(istream &is,mystr &ss)
{
is >> ss.str;
return is;
}
};
对[]重载
class point
{
private:
int a;
public:
point(int n):a(n){}
int get(){ return a; }
};
class Array
{
private:
point *p;
public:
point& operator[](int n)
{
assert(n >=0 && n < size);// 限定n的范围
return p[n];
}
}
int main()
{
point p0(22);
Array a1(2,p0);
cout << a1[0].get() << endl;
// 这里把a1当作数组看,通过下标访问
}
对<和==的重载
class mystr
{
private:
char *str;
int size;
public:
bool operator<(mystr &ss)
{
if(str[0] < ss.str[0]) return true;
int i = 0;
while(i < size && i < ss.size)
{
if(str[i] == ss.str[i]) i++;
else if(str[i] < ss.str[i]) return true;
else if(str[i] > ss.str[i]) return false;
}
return (size < ss.size ? true : false);
}
bool operator==(mystr &ss)
{
if(size != ss.size) return false;
for(int i = 0;i < size;i++)
if(str[i] != ss.str[i]) return false;
return true;
}
// 大于号和不等于的也是一个思路,反过来即可
}