程序设计与算法(三)C++面向对象程序设计 第四周 相关笔记
1、
运算符重载
#include<bits/stdc++.h> using namespace std; class Complex{ public: double r,i; Complex(double rr = 0,double ii = 0):r(rr),i(ii){} Complex operator-(Complex&b); void output(){ cout<<r<<" "<<i<<endl; } }; Complex operator+(Complex &a,Complex &b){ return Complex(a.r+b.r,a.i+b.i); } Complex operator*(Complex &a,Complex &b){ return Complex(a.r*b.r-a.i*b.i,a.r*b.i+a.i*b.r); } Complex Complex::operator-(Complex&b){ return Complex(r-b.r,i-b.i); } int main(){ Complex a(1,3),b(4,5),c; c = a+b; c.output(); c = a-b; c.output(); c = a*b; c.output(); return 0; } 输出: 5 8 -3 -2 -11 17

2、
赋值运算符的重载
#include<bits/stdc++.h> using namespace std; class Complex{ public: double r,i; Complex(double rr = 0,double ii = 0):r(rr),i(ii){} void output(){ cout<<r<<" "<<i<<endl; } void operator=(double rr); }; void Complex::operator=(double rr){ r = rr; } int main(){ Complex a; a = 2; a.output(); a = 2.214; a.output(); return 0; }
3、
运算符重载为友元
#include<bits/stdc++.h> using namespace std; class Complex{ private: double r,i; public: Complex(double rr = 0,double ii = 0):r(rr),i(ii){} void output(){ cout<<r<<" "<<i<<endl; } void operator=(double rr); Complex operator+(double add){ return Complex(r+add,i); } friend Complex operator+(double add,Complex &a); }; void Complex::operator=(double rr){ r = rr; } Complex operator+(double add,Complex &a){ return Complex(add+a.r,a.i); } int main(){ Complex a(2,3); a.output(); a = a+2; a.output(); a = 2+a; a.output(); return 0; } 输出: 2 3 4 3 6 3
4、
类型转换运算符的重载
#include<bits/stdc++.h> using namespace std; class Complex{ private: double r,i; public: Complex(double rr = 0,double ii = 0):r(rr),i(ii){} operator double(){ return r; } }; int main(){ Complex a(2,3); cout<<(double)a<<endl; double n = 3 + a; cout<<n<<endl; return 0; }
5、
++ --的重载
#include<bits/stdc++.h> using namespace std; class Complex{ private: double r,i; public: Complex(double rr = 0,double ii = 0):r(rr),i(ii){} operator double(){ return r; } Complex operator++(){ r++; return Complex(r,i); } }; int main(){ Complex a(2,3); cout<<(double)a<<endl; cout<<(++a)<<endl; return 0; }


浙公网安备 33010602011771号