C++中提供了运算符重载的功能,在大型项目中可以实现泛型,本例以++运算符为例,进行运算符重载,代码:
#include <iostream>
using namespace std;
class num
{
public:
num()
{
n = 1;
}
int get()
{
return n;
}
void operator++()
{
n++;
}
private:
int n;
};
int main (void)
{
num a;
cout << "a:" << a.get() << endl;
++a;
cout << "a:" << a.get() << endl;
}
这里的operator是C++的关键字,它用来重载一个运算符,本例中可以实现对对象进行++操作,实现的功能是将私有变量n进行自加一的操作。运行结果: