C++中的运算符重载
2017-12-16 00:26
113 查看
C++中的重载运算符
运算符重载的本质就是函数重载
1.1 语法格式:
例如:
1.1.1 友元、成员函数重载
运行结果:
1.1.2 双目运算符的重载
例如:
1.1.3 不能重载的运算符只有四个:
运算符重载的本质就是函数重载
1.1 语法格式:
返回类型 operator 运算符名称(形参表列) { 重载实体; }
例如:
const Complex operator+(const Complex &c1,const Complex &c2);//operator+重载了运算符+。
1.1.1 友元、成员函数重载
#include <iostream> using namespace std; class Complex { public: Complex(float x=0, float y=0) :_x(x),_y(y){} void dis() { cout<<"("<<_x<<","<<_y<<")"<<endl; } friend const Complex operator+(const Complex &c1,const Complex &c2); const Complex operator+(const Complex &another); private: float _x; float _y; }; const Complex operator+(const Complex &c1,const Complex &c2) { cout<<"友元函数重载"<<endl; return Complex(c1._x + c2._x,c1._y + c2._y); } const Complex Complex::operator+(const Complex & another) { cout<<"成员函数重载"<<endl; return Complex(this->_x + another._x,this->_y + another._y); } int main() { Complex c1(2,3); Complex c2(3,4); c1.dis(); c2.dis(); // Complex c3 = c1+c2; // Complex c3 = operator+(c1,c2); Complex c3 = c1+c2; //优先调用成员函数重载?? c3.dis(); return 0; }
运行结果:
(2,3) (3,4) 成员函数重载 (5,7)
1.1.2 双目运算符的重载
形式 L#R 全局函数 operaror#(L,R); 成员函数 L.operator#(R);
例如:
#include <iostream> using namespace std; class Complex { public: Complex(float x=0, float y=0) :_x(x),_y(y){} void dis() { cout<<"("<<_x<<","<<_y<<")"<<endl; } Complex & operator+=(const Complex &c) { this->_x += c._x; this->_y += c._y; return * this; } private: float _x; float _y; }; int main() { // int a = 10, b = 20,c = 30; // a += b; // b += c; // cout<<"a = "<<a<<endl; // cout<<"b = "<<b<<endl; // cout<<"c = "<<c<<endl; // Complex a1(10,0),b1(20,0), c1(30,0); // //(1)此时的+=重载函数返回 void // a1 += b1; // b1 += c1; // a1.dis(); // b1.dis(); // c1.dis(); //---------------------------------------------------- // int a = 10, b = 20,c = 30; // a += b += c; // cout<<"a = "<<a<<endl; // cout<<"b = "<<b<<endl; // cout<<"c = "<<c<<endl; // Complex a1(10,0),b1(20,0), c1(30,0); // //(2)此时重载函数+=返回的是 Complex // a1 += b1 += c1; // a1.dis(); // b1.dis(); // c1.dis(); //---------------------------------------------------- int a = 10, b = 20,c = 30; (a += b) += c; cout<<"a = "<<a<<endl; cout<<"b = "<<b<<endl; cout<<"c = "<<c<<endl; Complex a1(10,0),b1(20,0), c1(30,0); ////(3)此时重载函数+=返回的是 Complex & // 一定要注意在连等式中,返回引用和返回对象的区别 (a1 += b1) += c1; a1.dis(); b1.dis(); c1.dis(); return 0; }
1.1.3 不能重载的运算符只有四个:
. (成员运算符) ::(域解析运算符) ?:(条件运算符) sizeof(类型大小运算符)
相关文章推荐
- C++中运算符重载
- 转载 C++的运算符重载
- 【C++】类和对象--基础知识+四个默认成员函数+运算符重载
- c++学习笔记5:运算符重载、友元和类的类型转换
- 【C++学习历程5】运算符重载
- C++_运算符重载
- 运算符重载编程题3(C++程序设计第4周)
- C++之运算符重载(1)
- 北大 C++ 4.1 运算符重载
- c++学习笔记--由复数类看运算符重载
- C++的运算符重载
- C++之------运算符重载
- C++程序设计(9)之运算符重载
- 运算符重载-编程题#2(C++程序设计第4周)
- C++中,将class转换成函数指针(使用运算符重载实现,即operator函数)
- C++_运算符重载 再思考
- C++ 运算符重载
- C++中类型转换与函数、运算符重载的问题(中)
- 【C/C++开发】运算符重载
- C++:运算符重载函数之友元运算符重载