成员函数重载是指在同一个类里,有两个以上的函数具有相同的函数名。每种实现对应着一个函数体,但是形参的个数或者类型不同。
例如:减法函数重载
创建一个类,在类中定义3个名为subtract的重载成员函数,分别实现两个整数相减、两个实数相减和两个复数相减的功能。
#include <iostream>
using namespace std;struct Complex //复数类型
{double real;//实部double imag;//虚部
};class Sub //减法重载类
{
public:int subtract(int x, int y); //两个整数相减double subtract(double x, double y); //两个double相减Complex subtract(const Complex &x, const Complex &y);//两个复数相减
};int Sub::subtract(int x, int y)//两个整数相减
{return x - y;
}
double Sub::subtract(double x, double y)//两个double相减
{return x - y;
}
Complex Sub::subtract(const Complex& x, const Complex& y)//两个复数相减
{Complex c;c.real = x.real - y.real; //实部相减c.imag = x.imag - y.imag; //虚部相减return c;
}int main()
{int m = 30;int n = 20;double x = 34.5;double y = 23.2;Complex a = {10,10};Complex b = { 5,5 };Sub s;cout << m << " - " << n << " = " << s.subtract(m, n) << endl;cout << x << " - " << y << " = " << s.subtract(x, y) << endl;Complex c = s.subtract(a, b);cout << "(" << a.real << "+" << a.imag<< "i)" << " - " << "(" << b.real << "+" << b.imag << "i)"<< " = " << "(" << c.real << "+" << c.imag << "i)" << endl;return 0;
}
程序运行结果如下: