操作符重载的两种用法(前置后置++)
来源:互联网 发布:js 全等 编辑:程序博客网 时间:2024/05/31 05:27
一.操作符重载基础:
运算符函数是一种特殊的成员函数或友元函数
1.重载为类成员函数,解释为:
ObjectL.operator op(ObjectR)
左操作数由ObjectL通过this指针传递,右操作数由参数ObjectR传递
2.重载为友元函数,解释为:
operator op(ObjectL,ObjectR)
左右操作数都由参数传递
3.为什么要有操作符重载
a=a+b;//int是基础类型,c++编译器已经为这些类型提供+操作
Complex c1=c1+c2;//Complex是自定义类型,编译器根本不知道如何加,但c++编译器会给你提供一个机制,让你实现自定义类型+
例子代码如下,重要的地方有标记:
class Complex{
friend Complex operator+(Complex &c1, Complex &c2);
friend Complex& operator++( Complex &c2);//前置++友元函数的实现
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
void print()
{
cout << a << "+" << b << "i" << endl;
}
private:
int a;
int b;
//通过类的成员函数实现-操作;左操作数被隐藏在this指针,右操作数就在参数中
public:
Complex operator-(Complex &c2)
{
Complex tmp;
tmp.a = this->a - c2.a;
tmp.b = this->b - c2.b;
return tmp;
}
public:
Complex& operator--()//通过类的成员函数实现--操作;左操作数被隐藏在this指针,右操作数就在参数中
{
this->a--;
this->b--;
return *this;
}
};
Complex operator+(Complex &c1, Complex &c2)//全局函数实现+操作写法
{
Complex tmp;
tmp.a = c1.a + c2.a;
tmp.b = c1.b + c2.b;
return tmp;
}
Complex& operator++( Complex &c2)//全局函数实现++操作写法
{
c2.a++;
c2.b++;
return c2;
}
void main()
{
Complex c1(1, 2), c2(3, 4);
Complex c3;
c3.print();
Complex c4 = operator+(c1,c2);//友元函数的写法
c4.print();
Complex c7= c1+c2;//友元函数的写法
c7.print();
Complex c5 =c1.operator-(c2);//累的成员函数写法
c5.print();
Complex c6 = c1-c2;
c6.print();
++c2;
c2.print();
--c2;
c2.print();
system("pause");
}
//后置--
Complex operator--(int)
{
Complex tmp = *this;
this->a --;
this->b --;
return tmp;
}
//后置++
Complex operator++(int)
{
Complex tmp = *this;
this->a ++;
this->b ++;
return tmp;
}
二.操作符重载的三个步骤(类成员函数方法进行的时候)
//目标:通过类的成员函数,完成操作符重载
1.要承认操作符重载是一个函数,完成操作符重载
2.写出函数调用语言 c1.operator-(c2)
3.完善函数原型
全局函数重载操作符友元用武之地
原因:
cout<<c1<<"链式编程测试"<<endl;
operator<<(cout,c1);
cout.operator<<(c1);
- 操作符重载的两种用法(前置后置++)
- 操作符重载前置和后置的区别与实现
- 重载操作符++,区别前置和后置
- 运算符前置++和后置++的重载
- ++运算符的重载前置与后置
- 前置和后置++运算符的重载
- 重载 ++ , - - (前置 和 后置)
- 关于类重载前置++和后置++的骚操作
- C++中前置操作符和后置操作符以及解引用的重载
- [C++] C++的运算符重载(+、-、前置--、后置--,前置++,后置++、==)
- [C++] C++的运算符重载(+、-、前置--、后置--,前置++,后置++、==)
- 对象前置++,前置--;后置++,后置--(没有利用《和》重载运算符)
- Time类中的运算符重载(3)-前置++,后置++
- 实现前置与后置递增(递减)运算符的重载
- 前置++与后置++重载
- 前置++和后置++重载
- 关于前置操作符和后置操作符的区别
- 一元操作符重载 ,请注意前置和后置会有区别,友元函数的真正用途
- JPA持久化异常:PersistenceException: org.hibernate.PersistentObjectException
- SaaS厂商纷纷裁员?如何才能“活得”更久?
- 【DAG && 拓扑】POJ
- 软件设计文档国家标准
- 面向对象基础
- 操作符重载的两种用法(前置后置++)
- 数组二
- ios修改状态栏的颜色
- 每日一题(7) —— 求余运算符
- 【CS231N】Numpy 使用入门 (4)
- windows 安装redis
- 最短路径问题
- G
- HDU 2030