运算符重载---基本概念
C++程序设计
郭炜 刘家瑛
1 #include<iostream> 2 using namespace std; 3 class Complex{ 4 private: 5 double real; 6 double imaginary; 7 public: 8 Complex(double a=0.0,double b=0.0) : real(a),imaginary(b) {}//初始化 9 ~Complex(){} 10 Complex operator+(Complex& a); 11 Complex operator-(Complex& b); 12 void print(); 13 }; 14 Complex Complex::operator+(Complex& a){ 15 return Complex(real+a.real,imaginary+a.imaginary); 16 }//运算符重载函数(作为成员函数) 17 Complex Complex::operator-(Complex& a){ 18 return Complex(real-a.real,imaginary-a.imaginary); 19 }//运算符重载函数(作为成员函数) 20 void Complex::print(){ 21 cout<<real<<"+"<<imaginary<<"i"<<endl; 22 } 23 int main() 24 { 25 Complex x,y(3,7),z(2,3); 26 x=y+z;//相当于y.operator+(z),z为参数 27 x.print(); 28 x=y-z;//相当于y.operator-(z),z为参数 29 x.print(); 30 return 0; 31 }
时间: 2024-10-05 05:00:12