一. 函数重载
定义:声明几个功能类似的同名函数,但这些函数形参的个数、类型、顺序(至少其一)必须不同,返回类型必须相同。
例子:
#include<iostream>
using namespace std;
class printData
{
public:
void print(int i) {
cout << "整数为:" << i << endl;
}
void print(double f) {
cout << "浮点数为:" << f << endl;
}
void print(char c[]) {
cout << "字符串为:" << c << endl;
}
};
int main(void)
{
printData pd;
pd.print(3);//输出整数
pd.print(30.444);//输出浮点数
char c[] = "Hello C++";
pd.print(c);//输出字符串
return 0;
}
结果:
二.运算符重载
重载运算符后可以使用自定义类型的运算符
重载的运算符实质上是一个函数,这个函数的函数名的组成为:operator运算符
整体的函数为:返回值类型 函数名(参数列表)
运算符函数构成:返回值类型 operator运算符 (参数列表)
eg:Complex operator+(const Complex&);
此函数可为成员函数 或 非成员函数
例子:
#include<iostream>
using namespace std;
class Box
{
public:
double getVolume() {
return length * breadth * height;//计算体积
}
//设置长宽高
void setLength(double len) {
length = len;
}
void setBreadth(double bre) {
breadth = bre;
}
void setHeight(double hei) {
height = hei;
}
//重载运算符+,用于把两个对象相加
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.breadth;
return box;
}
private:
double length; //长
double breadth; //宽
double height; //高
};
int main()
{
Box box1, box2, box3;
double volume = 0.0;
box1.setLength(1.0);
box1.setBreadth(2.0);
box1.setHeight(3.0);
box2.setLength(2.0);
box2.setBreadth(2.0);
box2.setHeight(2.0);
volume = box1.getVolume();
cout << "volume of box1:" << volume << endl;
volume = box2.getVolume();
cout << "volume of box2:" << volume << endl;
box3 = box1 + box2;
volume = box3.getVolume();
cout << "volume of box3:" << volume << endl;
return 0;
}
结果:
如有错误,还请指正。