C++程序设计--运算符重载

目录

1, 运算符重载
2, 赋值运算符的重载
3, 流插入运算符重载
4,自加/自减运算符的重载

运算符重载

作用:对抽象数据类型也能够直接使用C++提供的运算符。
使得程序更简洁。
代码更容易理解。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
返回值类型 operator运算符 (形参表)
{
...
}
class Complex
{
public:
Complex(double r = 0.0, double i = 0.0);
Complex operator+(const Complex c1);
Complex operator-(const Complex c1);
double real;
double imag;
};
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
Complex Complex::operator+(const Complex c1)
{
return Complex(real + c1.real, imag + c1.imag);
}
Complex Complex::operator-(const Complex c1)
{
return Complex(this->real - c1.real, this->imag - c1.imag);
}
//普通类型的运算符重载
Complex operator+ (const Complex c1, const Complex c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}

运算符可以重载成普通函数,也能重载为成员函数。前者的参数个数就是对应操作符的目数,而成员函数则是目数减一。

赋值运算符的重载

1,赋值运算符两边的类型可以不匹配。
如:将一个Int类型的变量赋值给一个Complex对象。
2,对一个自己写的类想要进行 = 赋值时,需要重载赋值运算符”=”
3,赋值运算符“=”只能重载为成员函数
一般来说,赋值运算符的重载的返回值是该对象本身的引用,来满足=的意义。

流插入运算符重载

cout本身就是ostream的一个对象,而cout<<其实是在ostream类中对<<进行了重载。
我们如果想通过<< >>来实现自己对应的对象的输入和输出,则可以自己来重载这两个运算符。
一般定义为全局函数,因为iostream类C++已经写好了。
比如实现对复数类的输入输出:

1
2
大专栏  C++程序设计--运算符重载class="line">3
4
5
6
7
8
9
10
11
ostream& operator<<(ostream& o, Complex& c)
{
o << c.real << "+" << c.imag << "i";
return o;
}
istream& operator>>(istream& i, Complex& c)
{
//先读进string里面再分别剥离出real imag
return i;
}

自加/自减运算符的重载

前置和后置有区别,
前置是一元运算符,后置是二元运算符。多出来的一个参数具体是啥无意义,只是为了标记这是一个后置运算符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class CDemo
{
public:
CDemo(int _n) :n(_n){};
CDemo operator++();
CDemo operator++(int);
//强制类型转化
operator int(){ return n; }
friend CDemo operator--(CDemo&);
friend CDemo operator--(CDemo&, int);
private:
int n;
};
//前置
CDemo CDemo::operator++()
{
n++;
return *this;
}
CDemo operator--(CDemo& d)
{
d.n--;
return d;
}
//后置
CDemo CDemo::operator++(int)
{
CDemo temp (*this);
n++;
return temp;
}
CDemo operator--(CDemo& d, int)
{
CDemo t = d;
d.n--;
return t;
}

注意:上面的demo中int作为一个类型强制转换运算符被重载,Demo s; (int)s等效于s.int()。
类型强制转换运算符被重载时,不能写返回值类型,实际上其返回值就是类型转换所代表的类型。

Tips:
1,C++不允许定义新的运算符。
2,重载后的运算符应该符合日常习惯。
3,重载运算符不能改变运算符的优先级。
4,以下运算符不能被重载。”.” “*” “::” “?”,sizeof
5,重载运算符(), [], ->或者赋值运算符时,只能被声明为类的成员函数。

原文地址:https://www.cnblogs.com/lijianming180/p/12256215.html