- 重载
- 一个与之前已经在该作用域声明过的函数或者方法具有相同名称的声明,但是他们的参数列表和定义实现不相同。重载声明,会根据传入类型的不用来选取最合适的定义。选取最优函数或者运算符的过程也叫重载决策。
#include <iostream>
using namespace std;
class PrintData {
public:
void print(int i) {
cout << "int i is :" << i << endl;
}
void print(float i) {
cout << "float i is :" << i << endl;
}
void print(double i) {
cout << "double i is :" << i << endl;
}
void print(int *i) {
cout << "ptr i is :" << *i << endl;
}
};
int main() {
PrintData print_line = PrintData();
print_line.print(1);
print_line.print(float (1.));
print_line.print(1.1245666666666666666666);
int i = 1;
print_line.print(&i);
return 0;
}
- 运算符重载
- 对象之间的相加,返回最终相同的对象,大多数的重载运算符可被定义为普通的非成员函数或者被定义为类成员函数。我们也可以为每次操作传递两个参数。定义自由化,完全靠自己。
#include <iostream>
using namespace std;
class Box{
private:
double length;
double breadth;
double height;
public:
double getVolume()
{
return length*breadth*height;
}
void setLength(double length){
this->length = length;
}
void setBreadth(double breadth){
this->breadth = breadth;
}
void setHeight(double height){
this->height = height;
}
Box operator+(const Box&b){
Box box;
box.length = this->length+b.length;
box.breadth = this->breadth+b.breadth;
box.height = this->height+b.height;
return box;
}
};
int main() {
Box Box1;
Box Box2;
Box Box3;
double volume;
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(8.0);
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
volume= Box1.getVolume();
cout<<"Volume of Box1:"<<volume<<endl;
// box2 的体积
volume = Box2.getVolume();
cout<<"Volume of Box2:"<<volume<<endl;
Box3 = Box1+Box2;
volume = Box3.getVolume();
cout<<"Volume of Box3:"<<volume<<endl;
return 0;
}