C++运算符重载笔记
来源:互联网 发布:喜欢成熟的女人 知乎 编辑:程序博客网 时间:2024/06/02 02:31
今天看了c++中的运算符重载,记录一下,以备后面查看:
- #include <iostream>
- using namespace std;
- class F{
- int n;
- int d;
- void reduce(){
- int mcd = maxcd(n < 0 ? -n : n, d);
- if(mcd != 1){
- n /= mcd;
- d /= mcd;
- }
- }
- public:
- F(int n=0, int d=1):n(n), d(d){
- if(d == 0) throw"分母不能为零";
- if(d < 0) {
- this->d = -this->d;
- this->n = -this->n;
- }
- reduce();
- cout << "F(" << n << '/' << d << ")" << endl;
- }
- static int maxcd(int a,int b){
- if(a == 0) return b;
- return maxcd(b%a, a);
- }
- friend ostream& operator<<(ostream& o,const F& f){
- o << f.n << '/' << f.d;
- return o;
- }
- friend F operator+(const F& lh,const F& rh){
- return F(lh.n * rh.d + lh.d * rh.n, lh.d * rh.d);
- }
- //成员函数,少一个参数(当前对象作为第一个操作数)
- F operator*(const F& rh)const{
- //匿名对象
- return F(n*rh.n, d*rh.d);
- }
- friend F operator~(const F& f){
- return F(f.d, f.n);
- }
- bool operator!()const{
- return n==0;
- }
- };
- int main(){
- F f1;
- F f2(3);
- F f3(6, 12);
- F f4(5, 3);
- F f5(2, 9);
- cout << f3 << ',' << f4 << endl;
- cout << F::maxcd(392, 856) << endl;
- cout << f3 + f4 << endl;
- cout << f3*f4 << f2 * f3 * f4 << endl;
- cout << "~f3 = " << ~f3 << endl;
- cout << "!f3 = " << !f3 << endl;
- return 0;
- }
注意点:
1、匿名对象
2、成员函数和友元函数对运算符重载的区别
3、临时变量只能传给引用常量(const F&),比如f1 + f2 + f3中f1 + f2返回的是一个临时变量
4、友元函数既可以在类内部实现,也可以在类外部实现,不属于类的成员函数
5、const加在方法上则说明该方法内的this指向的对象只能读取不可修改。
0 0
- 【笔记-C++】 运算符重载
- 《Inside C#》笔记(十一) 运算符重载
- C++-运算符重载
- [C++]重载运算符
- C#:运算符重载
- c++-++运算符重载
- C++:重载运算符
- 运算符重载(C++)
- [c++]运算符重载
- 【C++】运算符重载
- C++--------------------------------------------运算符重载
- C#:运算符重载
- C++:运算符重载
- C++:运算符重载
- C#:运算符重载
- [C++]运算符重载
- 【c++】运算符重载
- C++:运算符重载
- 正则表达式详解
- EFI GPT 预装win8下ubuntu12.04的安装与引导
- c++ list容器
- android Base64加密解密
- 条款 41: 区分继承和模板
- C++运算符重载笔记
- 【Python笔记】源码编译安装Python时,如何支持自定义安装的高版本openssl库
- 黑马程序员—————Objective—C概念
- PAT 1044. Shopping in Mars (25)
- Hadoop集群搭建(三台电脑)
- UML建模之时序图(Sequence Diagram)
- 1分钟让别人喜欢你(二)
- 构建百万级高性能Web网站-6 JDK+Nginx+Tomcat的安装
- day12_面向对象的包+多线程