运算符重载:
实质是函数重载,形式返回值类型 operator运算符(形参表){}
程序编译时:
1、把含运算符的表达式转换为运算符函数的调用
2、运算符的操作数转换为运算符函数的参数
3、运算符被多次重载时,根据实参的类型决定调用运算符函数
4、运算符可以被重载为普通函数,也可以被重载为成员函数。
重载为普通函数,参数个数为运算目数:
class Complex{
public:
int real;
int image;
public:
Complex(){}
Complex(int r,int i){
real = r;
image = i;
}
};
Complex operator+(const Complex& com1,const Complex & com2){
return (Complex(com1.real+com2.real,com1.image+com2.image));
}
int main() {
Complex a(1,2),b(3,4),c;
c = a
+ b;
cout<<c.real<<"\t"<<c.image<<endl;
return 0;
}
重载为成员函数,参数个数为运算目数减1:调用的是对象.+()
class Complex{
public:
int real;
int image;
public:
Complex(){}
Complex(int r,int i){
real = r;
image = i;
}
Complex operator+(const Complex & com2){
return Complex(this->real+com2.real,this->image+com2.image);
}
};
int main() {
Complex a(1,2),b(3,4),c;
c = a + b;
cout
<<c.
real
<<
"
\t
"
<<c.
image
<<endl;
return
0;
}
赋值运算符只能重载为成员函数:
class String{
char* str;
public:
String():str(NULL){}
char * operator=(const char * b){
if(str){
delete []str;
}
if (b){
str = new char[strlen(b)+1];
strcpy(str,b);
}
return str;
}
char * get_str(){
return str;
}
~String(){
if(!str){
delete [] str;
}
}
};
int main() {
String s;
s = "happy";
cout
<<s.get_str()
<<endl;
return
0;
}
}
深拷贝和浅拷贝:
浅拷贝:一个对象中指针变量的内容复制到另一个对象中指针成员对象所指向的内容。
带来的问题:会调用两次析构函数,第二次调用的时候变量已经被释放了,再去delete会导致错误
深拷贝:一个对象中指针变量所指向的内容复制到另一个对象中指针成员对象所指向的内容。
拷贝的时候会新创建一片空间,对其赋值。