前缀++ 后缀++ 运算符重载
下面例子程序中?? const Fraction operator ++(int)?? 中 ??
? int不過是個啞元(dummy),是永遠用不上的 ??
? 它只是用來判斷++是prefix ? 還是 ? postfix ??
? 記住,如果有啞元,則是postfix,否則,就是prefix???
? 就像其他的一元算法和邏輯運算一樣 ??
? 而其實在C++中用到這種啞元的也只有在postfix ? ++ ? 和--了
?例子:
int i=10;
cout<<i++<<endl;????//i=11;后綴加;先返回后自增;???10
cout<<++i<<endl;????//i=12;前綴加;先自增后返回;???12
例:
#include<iostream>
using namespace std;
class Fraction???????????????????????????????????????????//數(shù)類;
{
?friend ostream& operator<<(ostream& out, const Fraction& x);
private:
?int den;?????????????????????????????????????????//加的步進距離,使自加的距離不是1;
?int num;?????????????????????????????????????????//數(shù)(初值);
public:
?Fraction(int d=1, int n=0):den(d),num(n) {}
?Fraction& operator++()???????????????????????????//前綴自加重載;(前置版本prefix)
??{
???num+=den;????????????????????????//先自增,再返回;
???return *this;
??}
?const Fraction operator ++(int)??????????????????//后綴自加重載;(后置版本postfix)
??{
???Fraction old (*this);????????????//拷貝構造(對象參數(shù)是對象)。先返回,再自增;
???++(*this);???????????????????????//調(diào)用的是重載的前置版本;
???return old;
??}
};
ostream& operator<<(ostream& out, const Fraction& x)
{
?out<<x.num<<endl;
?return out;
}
int main()
{
?Fraction b(10,10);
?cout<<b++<<endl;
?cout<<++b<<endl;
?return 0;
}
前置版本返回一個引用【Fraction& operator++()】,后置版本返回一個const值【const Fraction operator ++(int)】。
后置版本是利用前置版本來實現(xiàn)的。節(jié)約代碼,控制代碼有余。
前置版本的效率高,因為后置版本需要調(diào)用前置版本,所有后置版本效率比前置要低。(++i比i++效率高。)
在后置版本里,人為添加一個參數(shù)(int),主要是為了區(qū)別前置版本,這個參數(shù)不會被使用。
總結
以上是生活随笔為你收集整理的前缀++ 后缀++ 运算符重载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NLP 学习笔记9-停用词
- 下一篇: gmssl编译