2018/2/6
C++
1.关于运算符的重载
1.运算符的重载的意义是实现运算符的重新操作
2.重载不能改变运算符运算对象(操作数)的个数
3.重载不能改变运算符的优先级别
4.重载不能改变运算符的结合性
5.重载运算符的函数不能有默认参数
6.重载运算符必须和用户自定义的类型一起使用、
2.注意:有五个运算符不允许重载
-.(成员访问运算符)
- .*(成员访问指针运算符)
-::(域运算符)
-sizeof(尺寸运算符)
-?;(基于三元运算的条件运算符)
3.text:用运算符的重载实现复数的加减
/*运算符的重载*/
/*text1 实现复数的加法*/
#include<iostream>
#include<stdlib.h>
using namespace std;
class Complex
{public:
Complex();
Complex(double a, double b);
Complex operator+(Complex &d);
void print();
protected:
double real;//实部
double imag;//虚部
};
/*初始化*/
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double a, double b)
{
/*实部虚部赋值*/
real = a;
imag = b;
}
Complex Complex::operator+(Complex &d)
{
Complex num;
num.real = real + d.real;
num.imag = imag + d.imag;
return num;
}
void Complex::print()
{
cout << "(" << real << "," << imag << "i" << ")" << endl;
}
int main()
{
Complex c1(3, 4), c2(5, -10), c3;
c3 = c1 + c2;//c3=c1.operator+c2,已经是重载后的加号了
cout << "c1=";
c1.print();
cout << "c2=";
c2.print();
cout << "c1+c2=";
c3.print();
system("pause");
}