1.重载赋值运算符

class Data
{
public:
Data(int y, int m, int d);
Data& operator=(Data &p);
void print();
private:
int year, month, day;
};
Data::Data(int y, int m, int d)
{
this->year = y;
this->month = m;
this->day = d;
}
Data& Data::operator=(Data &p)
{
this->year = p.year;
this->month = p.month;
this->day = p.day;
return *this;
}
void Data::print()
{
cout << "year=" << this->year << "--" << "month=" << this->month << "--" << "day=" << this->day << endl;
}
int main()
{
Data p(2021,12,7); //创建并初始化
Data p2 = p;
p2.print();
return 0;
}

2.重载+号运算符

class score
{
public:
score(int ch, int ma, int eng);
void print();
score& operator+(score& p)
{
this->ch += p.ch;
this->ma += p.ma;
this->eng += p.eng;
return *this;
}
private:
int ch, ma, eng;
};
score::score(int ch, int ma, int eng)
{
this->ch = ch;
this->ma = ma;
this->eng = eng;
}
void score::print()
{
cout << "ch=" << this->ch << "--" << "ma=" << this->ma << "--" << "eng=" << this->eng << endl;
}
int main()
{
score p1(100, 100, 99);
score p2(0,0,0) ; //初始化为0
p2 = p1;
p2.print();
return 0;
}

重载其它乘除运算符类似

3.重载左移运算符

class score
{
friend ostream& operator<<(ostream& cout, score& p);
public:
score(int ch, int ma, int eng);
int ch, ma, eng;
};
score::score(int ch, int ma, int eng)
{
this->ch = ch;
this->ma = ma;
this->eng = eng;
}
ostream& operator<<(ostream& cout, score& p)
{
cout <<"ch="<<p.ch << endl;
cout << "ma="<<p.ma << endl;
cout <<"eng="<< p.eng << endl;
return cout;
}
int main()
{
score p(100, 100, 99);
cout << p;
return 0;
}

这个左移运算符只能放在全局函数位置,不能放在类中成员函数。

4.重载++运算符

class score
{
public:
friend ostream& operator<<(ostream& cout, score& p);
score& operator++()
{
ch += 1;
ma += 1;
eng += 1;
return *this;
}
public:
score(int ch, int ma, int eng);
int ch, ma, eng;
};
score::score(int ch, int ma, int eng)
{
this->ch = ch;
this->ma = ma;
this->eng = eng;
}
ostream& operator<<(ostream& cout, score& p)
{
cout <<"ch="<<p.ch << endl;
cout << "ma="<<p.ma << endl;
cout <<"eng="<< p.eng << endl;
return cout;
}
int main()
{
score p(100, 100, 99);
cout << (++p);
return 0;
}

--运算符类似。

5.重载()运算符

也叫仿函数。

void operator()(string name)
{
cout<<name<<endl;
}
//调用即
class Data p;
p("hello world");

!!!:不可重载运算符

​作用域解析操作符:  ::

条件运算符:   ?  :

直接成员访问运算符:  .

解除类成员指针引用运算符:  .*

sizeof运算符: sizeof


如有不对,欢迎指正。