目录
1. 运算符2. 自定义数据类型与运算符重载3. 运算符重载4. 运算符重载为普通函数5. 运算符重载为成员函数
1. 运算符
2. 自定义数据类型与运算符重载
3. 运算符重载
4. 运算符重载为普通函数
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
, const Complex
& b
)
{
return Complex(a
.real
+ b
.real
, a
.imaginary
+ b
.imaginary
);
}
Complex
a(1,2), b(2, 3), c
;
c
= a
+ b
;
重载为普通函数时,参数个数为运算符目数
5. 运算符重载为成员函数
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;
}
重载为成员函数时,参数个数为运算符数目减一
站在巨人的肩上 【1】北京大学信息技术学院《程序设计实习》
转载请注明原文地址:https://ipadbbs.8miu.com/read-65489.html