C++ Primer Plus学习笔记之运算符重载
1,成员函数和友元函数选择的建议 下面我们先看两个例子: 成员函数重载#includeusing namespace std; class Complex { public: Complex(double r=0,double i=0) { re=r; im=i; } Complex operator+(const Complex& obj); Complex operator!(); void Display(); private: double re; double im; }; Complex Complex::operator+(const Complex& obj) { Complex temp; temp.re=re+obj.re; temp.im=im+obj.im; return temp; } Complex Complex::operator!() { Complex temp; temp.re=re; temp.im=-im; return temp; } void Complex::Display() { cout< 0) cout<<"+"< 友元函数重载 #includeusing namespace std; class Complex { public: Complex(double r=0,double i=0) { re=r; im=i; } friend Complex operator+(const Complex& obj1,const Complex& obj2); Complex operator!(); void Display(); private: double re; double im; }; Complex operator+(const Complex& obj1,const Complex& obj2) { Complex temp; temp.re=obj1.re+obj2.re; temp.im=obj1.im+obj2.im; return temp; } Complex Complex::operator!() { Complex temp; temp.re=re; temp.im=-im; return temp; } void Complex::Display() { cout< 0) cout<<"+"< 对于成员函数重载,由于obj3=27+obj1的显示调用为obj3=27.operator+(obj1),而27不是Complex类型,因此编译器不能调用Complex的operator+()重载运算符完成加法操作; 对于友元函数重载,由于obj3=27+obj1的调用通过有一个参数缺省的构造函数Complex(double r=0,double i=0), 系统可以自动将27转换为Complex(27)对象,因此编译通过; 由此可知,成员函数仅仅能为一个实际对象所调用,友元无此限制。因此若运算符的操作需要修改类对象的状态,则它应该是成员函数,而不应该是友元。相反,如果运算符的操作数(尤其是第一个操作数)希望有隐式类型转换,则该运算符重载必须用友元函数,而不是成员函数。 2,重载++的前缀和后缀 成员函数重载 #include using namespace std; class Complex { public: Complex(double r=0,double i=0) { re=r; im=i; } friend Complex operator+(const Complex& obj1,const Complex& obj2); Complex& operator++();//前缀方式 Complex operator++(int);//后缀方式 Complex operator!(); void Display(); private: double re; double im; }; Complex operator+(const Complex& obj1,const Complex& obj2) { Complex temp; temp.re=obj1.re+obj2.re; temp.im=obj1.im+obj2.im; return temp; } Complex& Complex::operator++() { re++; im++; return *this; } Complex Complex::operator++(int)//int为占位符 { Complex temp(*this);//拷贝构造函数 re++; im++; return temp; } Complex Complex::operator!() { Complex temp; temp.re=re; temp.im=-im; return temp; } void Complex::Display() { cout<0) cout<<"+"< #include using namespace std; class Complex { public: Complex(double r=0,double i=0) { re=r; im=i; } friend Complex operator+(const Complex& obj1,const Complex& obj2); friend Complex& operator++(Complex& obj);//前缀方式 friend Complex operator++(Complex& obj,int);//后缀方式 Complex operator!(); void Display(); private: double re; double im; }; Complex operator+(const Complex& obj1,const Complex& obj2) { Complex temp; temp.re=obj1.re+obj2.re; temp.im=obj1.im+obj2.im; return temp; } Complex& operator++(Complex& obj) { obj.re++; obj.im++; return obj; } Complex operator++(Complex& obj,int)//int为占位符 { Complex temp(obj);//拷贝构造函数 obj.re++; obj.im++; return temp; } Complex Complex::operator!() { Complex temp; temp.re=re; temp.im=-im; return temp; } void Complex::Display() { cout< 0) cout<<"+"< 首页 上一页 1 2 3 下一页 尾页 1/3/3