函数重载
我们明白函数重载的作用就可以明白函数重载该如何写了。简单的说函数重载是为了实现某种意义上的多态,这种多态呢?简单点讲,同一个函数,传入不同的参数,有不同的表现。所以我们知道函数重载至少有两个函数,并且函数名字需要一样。因为要有不同的不同的参数,所以形参列表不能完全一样。我们知道一个函数有三部分,返回值,函数名,传入值。现在函数名一样,传入值不一样,那么返回值呢?根据定义知道返回值一样不一样都无所谓,因为当我们调用一个函数时不会去理会它的返回值。因此我们知道两个函数只有返回值得类型不一样,不算是函数重载,而是函数的重复定义。
#include <iostream>
using namespace std;
class Print{
public:
void print()
{
cout << "i am print()" << endl;
}
void print(int i)
{
cout << "i am print("<< i << ")" << endl;
}
void print(char c)
{
cout << "i am print(" << c << ")" << endl;
}
};
int main()
{
Print p;
p.print();
p.print(3);
p.print('c');
return 0;
}
运行结果:
i am print()
i am print(3)
i am print(c)
其实拷贝构造函数和构造函数,就属于函数重载。
运算符重载
运算符重载,先说一下有神马作用吧!例如我们重载‘+’运算符,‘+’普通来说只能对两个数进行加法运算,但我们想直接对两个对象,或者两个矩阵进行加法运算,使用普通的加法无法满足我们的需求,所以需要重载运算符,然后定义自己的加法运算。
重载运算符的定义形式:
type operator‘重载的运算符’(const type& a,const type& b)
看一下具体的代码:
#include <iostream>
using namespace std;
class Box{
public:
int width;
int height;
Box operator+(const Box& a)
{
Box box;
box.width = this->width + a.width;
box.height = this->height + a.height;
return box;
}
};
int main()
{
Box box1,box2,box3;
box1.width = 10;
box1.height = 20;
box2.width = 3;
box2.height = 5;
box3 = box1+box2;
cout << "box1(width,height):(" <<box1.width << ','<<box1.height << ")" << endl;
cout << "box2(width,height):(" <<box2.width << ','<<box2.height << ")" << endl;
cout << "box3(width,height):(" <<box3.width << ','<<box3.height << ")" << endl;
return 0;
}
运行结果:
box1(width,height):(10,20)
box2(width,height):(3,5)
box3(width,height):(13,25)