在同一个作用域内,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同。不能仅通过返回类型的不同来重载函数。
下面的实例中,同名函数 print() 被用于输出不同的数据类型:
#include <iostream>
using namespace std;
class Printf
{
public :
void print( int x )
{
cout << "int = " << x << endl;
}
void print( double x )
{
cout << "float = " << x << endl;
}
void print( char x[] )
{
cout << "char [] = " << x << endl;
}
};
int main()
{
Printf Pf;
Pf.print(5);
Pf.print(8.8);
Pf.print("abc");
return 0;
}
我们可以重定义或重载大部分 C++ 内置的运算符。这样就能使用自定义类型的运算符。
下面的实例中,+运算符被用于Box对象的加法:
#include <iostream>
using namespace std;
class Box
{
public:
int getVolume()
{
return (width * height *length);
}
void setWidth( float x )
{
width = x;
}
void setHeight( float x )
{
height = x;
}
void setLehgth( float x )
{
length = x;
}
Box operator+( const Box& x )
{
Box Res;
Res.width = x.width + this->width;
Res.height = x.height + this->height;
Res.length = x.length + this->length;
return Res;
}
protected:
float width;
float height;
float length;
};
int main()
{
Box box1,box2,box3;
float Box1Volume , Box2Volume , Box3Volume;
box1.setWidth(1);
box1.setHeight(2);
box1.setLehgth(3);
box2.setWidth(4);
box2.setHeight(5);
box2.setLehgth(6);
Box1Volume = box1.getVolume();
Box2Volume = box2.getVolume();
cout << Box1Volume << endl;
cout << Box2Volume << endl;
box3 = box1 +box2;
Box3Volume = box3.getVolume();
cout << Box3Volume << endl;
return 0;
}