C++ Integer ++运算符重载
一、整体代码
Integer.h
[cpp]
#ifndef _INTEGER_H_
#define _INTEGER_H_
class Integer
{
public:
Integer(int n);
~Integer();
Integer(const Integer& other);//拷贝构造函数
Integer& operator++();
//friend Integer& operator++(Integer& i);
Integer operator++(int n);
//friend Integer operator++(Integer& i, int n);
void Display() const;
private:
int n_;
};
#endif // _INTEGER_H_
Integer.cpp
[cpp]
#include"Integer.h"
#include<iostream>
usingnamespace std;
Integer::Integer(int n) : n_(n)
{
}
Integer::~Integer()
{
}
Integer::Integer(const Integer& other) : n_(other.n_)
{
//num_ = other.num_;
cout<<"Initializing with other "<<n_<<endl;
}
Integer& Integer::operator++()
{
//cout<<"Integer& Integer::operator ++()"<<endl;
++n_;
return*this;//返回自身引用
}
//Integer& operator++(Integer& i)
//{
// cout<<"Integer& operator++(Integer& i)"<<endl;
// ++i.n_;
// return i;
//}
Integer Integer::operator++(int n)
{
//cout<<"Integer& Integer::operator ++()"<<endl;
//n_++;
Integer tmp(n_);
n_++;
return tmp;
}
//Integer operator++(Integer& i, int n)
//{
// Integer tmp(i.n_);
// i.n_++;
// return tmp;
//}
void Integer::Display() const
{
cout<<n_<<endl;
}
01.cpp
[cpp]
#include "Integer.h"
#include <iostream>
using namespace std;
int main(void)
{
Integer n(100);
n.Display();//显示100
Integer n2 = ++n;//Integer n2 = n.operator++();把自身调用返回,赋给n2,调用了一次拷贝构造函数,Initializing with other 101
n.Display();//101
n2.Display();//101
Integer n3 = n++;//Integer n3 = n.operator++(int n);把原来临时的对象(n_为101)由n3接管,不调用拷贝构造函数
n.Display();//102
n3.Display();//101
return 0;
}
二、解释
如果只是调用++n;再调用n.Display();也显示101。
补充:软件开发 , C++ ,