1、函数重载:重载条件 =( 参数类型不同 || 参数个数不同 || 参数顺序不同 )
#include <iostream>
using namespace std;
int myAdd(int x, int y)
{
return x+y;
}
double myAdd(double x, double y)
{
return x + y;
}
int main(int argc, char* argv[])
{
cout << "12 + 32 = " << myAdd(12, 32) << endl;
cout << "11.1 + 22.2 = " << myAdd(11.1, 22.2) << endl;
return 0;
}
| xuanmiao@linux:~/Test/C++$ ./test29 12 + 32 = 44 11.1 + 22.2 = 33.3 |
2、运算符重载:operator +
#include <iostream>
using namespace std;
class CPerson
{
private:
int money;
public:
CPerson(int inMoney)
{
money = inMoney;
}
/* 对象和对象运算*/
CPerson operator+ (const CPerson &b)
{
return CPerson(money + b.money);
}
/* 对象和基本类型数据运算 */
CPerson operator+ (const int intMoney)
{
return CPerson(money + intMoney);
}
void display(void)
{
cout << money << endl;
}
};
int main( int argc, char *argv[] )
{
CPerson person1(10);
CPerson person2(20);
CPerson person3 = person1 + person2;
CPerson person4 = person3 + 100;
person3.display();
person4.display();
return 0;
}
| xuanmiao@linux:~/Test/C++$ ./test30 30 130 |
函数重载和运算符重载
浙公网安备 33010602011771号