c++运算符的重载
来源:互联网 发布:重生之一叶而知秋书包 编辑:程序博客网 时间:2024/06/02 06:39
先通过一个例子理解运算符的重载
#include<iostream>using namespace std;class Complex{private: double real;//实部 double imag;//虚部public: Complex(double real = 0, double imag = 0);//构造函数 ~Complex();//析构函数 void display();//显示 Complex operator+(Complex &y);//重载运算符};Complex::Complex(double real, double imag){ this->real = real; this->imag = imag;}Complex::~Complex(){ cout << "Finished" << endl;}Complex Complex::operator + (Complex &y){ return Complex(real+y.real,imag+y.imag);}void Complex::display(){ cout << real << "+" << imag << "i" << endl;}int main(){ Complex x(1.9, 1.2), y(2, 8), z; z = x + y; z.display(); system("pause"); return 0;}
C++运算符重载的一些规定
1. C++不允许用户自己定义新的运算符,只能对已有的运算符进行重载
2.不能重载的运算符有5个
3.重载不能改变运算符运算对象的个数
4. 重载不能改变运算符的优先级别
5. 重载不能改变运算符的结合性
6.重载运算符不能有默认的参数
7.重载运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应有一个是类对象(或类对象的引用)
8. 用于类对象的运算符一般必须重载,但有两个例外“=”“&”
9.理论上讲,可以将运算符重载为执行任意的操作
对运算符重载的函数有两种处理方式
1.作为类的成员函数
2.作为类的友元函数
c++对个别运算符有一些强制规定
双目运算符的重载
#include<iostream>using namespace std;class String{private: char *p;public: String(char *p = NULL);//带默认参数的构造函数 ~String();//析构函数 void set(char *p); void display();//显示 friend bool operator>(String &a, String &b);//重载 > friend bool operator<(String &a, String &b);//重载 < friend bool operator==(String &a, String &b);//重载 ==};String::String(char *p ){ set(p);}String::~String(){ cout << "finished" << endl;}void String::set(char *p){ this->p = p;}void String::display(){ cout << p << endl;}bool operator>(String &a, String &b){ if (strcmp(a.p, b.p)>0) return true; else return false;}bool operator<(String &a, String &b){ if (strcmp(a.p, b.p)<0) return true; else return false;}bool operator==(String &a, String &b){ if (strcmp(a.p, b.p)==0) return true; else return false;}int main(){ String s1("hello"), s2("hello"); cout << (s1 > s2) << endl; cout << (s1 < s2) << endl; cout << (s1 == s2) << endl<<endl; s1.set("asasaaas"); cout << (s1 > s2) << endl; cout << (s1 < s2) << endl; cout << (s1 == s2) << endl; system("pause"); return 0;}
重载单目运算符
未完,待续。。。
阅读全文
0 0
- c++-运算符的重载
- C++--运算符的重载
- [C/C++]运算符的重载
- C++-运算符重载
- [C++]重载运算符
- C#:运算符重载
- c++-++运算符重载
- C++:重载运算符
- 运算符重载(C++)
- [c++]运算符重载
- 【C++】运算符重载
- C++--------------------------------------------运算符重载
- C#:运算符重载
- C++:运算符重载
- C++:运算符重载
- C#:运算符重载
- [C++]运算符重载
- 【c++】运算符重载
- SIGPIPE信号导致的进程崩溃
- 113. Path Sum II
- 28、数组中出现次数超过一半的数字
- 【w1】微信公众号接口-微信接口怎么设置不弹出{“errMsg”:"config:ok"}
- java中的集合工具类Collections中的常用方法
- c++运算符的重载
- 隐私政策
- Android Launcher结构分析
- hdu1841Find the Shortest Common Superstring
- du查看磁盘空间
- Android网上资料
- js清空file选中的内容
- 《编写可维护的JavaScript》读书笔记(3) --语句和表达式
- Codeforces Round #376 (Div. 2) C. Socks —— 并查集 + 贪心