首先感谢@CFBDSIR2149的笔记整理,救我狗命(她的博客https://www.cnblogs.co/myqD-blogs/)

以下是我参考各种资料课件(主要是mooc)等,只针对我自己的注意点,并且可能有错误的地方,也欢迎指出(如果有人看的话)

mooc讲课老师的微博http://weibo.com/guoweiofpku,随笔大多都参考他的ppt

看到啥写啥,没有条理,甚至有我个人的日常生活记录

1.运算符重载,就是对已有的运算符(C++中预定义的运算符)赋予多重的含义,使同一运算符作用于不同类型的数据时导致不同类型的行为。

2.运算符重载的实质是函数重载

class Complex 
{
public:
double real,imag; 
Complex( double r = 0.0, double i= 0.0 ):real(r),imag(i) { }
Complex operator-(const Complex & c); 
};
Complex operator+( const Complex & a, const Complex & b)
{
return Complex( a.real+b.real,a.imag+b.imag); //返回一个临时对象
} 
Complex Complex::operator-(const Complex & c)
{
return Complex(real - c.real, imag - c.imag); //返回一个临时对象
}
int main()
{
Complex a(4,4),b(1,1),c;
c = a + b; //等价于c=operator+(a,b);
cout << c.real << "," << c.imag << endl;
cout << (a-b).real << "," << (a-b).imag << endl;
//a-b等价于a.operator-(b)
return 0;
}

3.赋值运算符“=”只能重载为成员函数

class String {
private: 
char * str;
public:
String ():str(new char[1]) { str[0] = 0;}
const char * c_str() { return str; };
String & operator = (const char * s);
String::~String( ) { delete [] str; }
};
String & String::operator = (const char * s) 
{ //重载“=”以使得 obj = “hello”能够成立
delete [] str;
str = new char[strlen(s)+1];
strcpy( str, s);
return * this;
}
v>

int main()

{

String s;

s = "Good Luck," ; //等价于 s.operator=("Good Luck,");

cout << s.c_str() << endl;

// String s2 = "hello!"; //这条语句要是不注释掉就会出错

s = "Shenzhou 8!"; //等价于 s.operator=("Shenzhou 8!");

cout << s.c_str() << endl;

return 0;

}

4.operator = 返回值类型最好是String &

 ————————————TBC————————————