运算符
- C++ 预定义表示对数据的运算
- C++ 提供了数据抽象的手段
用户自己定义数据类型 -- 类
- 类的成员函数 -> 操作对象时,很不方便
- 在数学上,两个复数可以直接进行+/-等运算,在 C++中,是不允许的。
运算符重载
- 对抽象数据类型也能够直接使用 C++提供的运算符
- 运算符重载
- 对已有的运算符赋予多重的含义
- 使同一运算符作用域不同类型的数据时->不同类型的行为
- 目的
- 扩展 C++中提供的运算符的适用范围,以用于类所表示的抽象数据类型
- 同一个运算符,对不同类型的操作数,所发生的行为不同
- (5,10i)+(4,8i) = (9,18i)
- 5 + 4 = 9
- 运算符重载的 实质 是 函数的重载
- 在程序编译时候:
- 把含运算符的表达式 -> 对 运算符函数的调用
- 把运算符的操作数 ->运算符函数的参数
- 运算符被多次重载时,根据 实参的类型 决定调用哪个运算符函数
- 运算符可以被重载成 普通函数
- 也可以被重载成 类的成员函数
- 运算符重载为普通函数
重载为普通函数时,参数个数为运算符目数
class Complex{
public:
Complex(double r = 0.0,double i = 0.0){
real = r;
imaginary = i;
}
double real;
double imaginary;
};
Complex operator+ (const Complex &a,cost Complex &b)
{
return Complex(a.real+b.real,a.imaginary+b.imaginary);
}//类名(参数表)就代表一个对象
Complex a(1,2),b(2,3),c;
c = a + b;//相当于什么?
//相当于调用了:
operator+(a,b);
- 运算符作为成员函数
重载为成员函数时,参数的个数为运算符目数减一
class Complex{
public:
Complex(double r = 0.0,double m = 0.0);
real(r),imaginary(m){ }
Complex operator+ (const Complex &);
Complex operator- (const Complex &);
private:
double real;
double imaginary;
};
Complex Complex::operator+(const Complex & operand2){
return Complex(real +operand2.real,imaginary+ operand2.imaginary);
}
Complex Complex::operator-(const Complex & operand2){
return Complex(real -operand2.real,imaginary- operand2.imaginary);
}
int main(){
Complex x,y(4.3,8.2),z(3.3,1.1);
x = y + z;
x = y - z;
return 0;
}
网友评论