C++之重载 重定义与重写用法详解
重载(Overload)
在C++中,重载指的是使用同一个函数名,但是参数类型或数量不同。在编译时,编译器根据实参的类型和数量,自动匹配相应的函数调用。函数的返回类型可以相同也可以不同。例如:
int add(int a, int b){
return a + b;
}
float add(float a, float b, float c){
return a + b + c;
}
在上面的代码中,add()函数被重载了两次,分别实现了两个不同的功能。第一个函数实现了两个整数的相加,第二个函数实现了三个浮点数的相加。在调用这两个函数时,编译器会根据实参的类型和数量,自动匹配相应的函数调用。
重定义(Override)
重定义指的是在派生类中重新定义(覆盖)基类中的同名函数。在重定义中,函数名和参数类型和数量都必须与基类函数完全相同。例如:
class Shape{
protected:
int width, height;
public:
void setWidth(int w){
width = w;
}
void setHeight(int h){
height = h;
}
virtual int area(){ // 虚函数
cout << "Parent's area: " << endl;
return 0;
}
};
class Rectangle:public Shape{
public:
int area(){ // 重定义虚函数
cout << "Rectangle's area: " << endl;
return (width * height);
}
};
在上面的代码中,基类Shape有一个虚函数area(),该函数被派生类Rectangle重定义(Override)。在调用Rectangle的area()函数时,会优先调用派生类中的函数。例如:
Shape* shape1 = new Shape(); // 声明基类指针
Shape* shape2 = new Rectangle(); // 声明派生类指针
// 调用基类成员函数 getWidth()
shape1->setWidth(5);
shape1->setHeight(7);
// 调用派生类成员函数 getWidth()
shape2->setWidth(5);
shape2->setHeight(7);
// 输出结果
cout << "Shape's area: " << shape1->area() << endl;
cout << "Rectangle's area: " << shape2->area() << endl;
以上代码中,shape1和shape2分别指向基类Shape和派生类Rectangle的对象。因为area()函数是虚函数,所以在调用shape2->area()时,会优先调用Rectangle中的area()函数,输出结果为"Rectangle's area:"。
重写(Redeclare)
重写指的是在同一个作用域中,根据需要多次声明同名标识符。在重写中,函数名和参数类型可以相同也可以不同,但是返回类型必须相同。例如:
int add(int a, int b){
return a + b;
}
int add(double a, int b){
return (int)a + b;
}
在上面的代码中,add()函数被重写了两次。第一个函数实现了两个整数的相加,第二个函数实现了一个double和一个整数的相加,将double类型的a强制转换为int类型。在调用这两个函数时,编译器会根据实参的类型和数量,自动匹配相应的函数调用。
示例1
下面的示例演示了重载的使用。它定义了两个函数,分别实现两个浮点数和三个浮点数的相加。当调用这两个函数时,编译器会根据实参的类型和数量,自动匹配相应的函数调用。
#include <iostream>
using namespace std;
float add(float a, float b){
return a + b;
}
float add(float a, float b, float c){
return a + b + c;
}
int main(){
cout << add(1.1f, 2.2f) << endl; // 输出3.3
cout << add(1.1f, 2.2f, 3.3f) << endl; // 输出6.6
return 0;
}
示例2
下面的示例演示了重定义的使用。它定义了两个类,分别是基类Shape和派生类Rectangle。在派生类Rectangle中,重定义了基类Shape的虚函数area()。当调用派生类的area()函数时,会优先调用派生类中的函数。
#include <iostream>
using namespace std;
class Shape{
protected:
int width, height;
public:
void setWidth(int w){
width = w;
}
void setHeight(int h){
height = h;
}
virtual int area(){
cout << "Parent's area: " << endl;
return 0;
}
};
class Rectangle:public Shape{
public:
int area(){
cout << "Rectangle's area: " << endl;
return (width * height);
}
};
int main(){
Shape* shape1 = new Shape(); // 声明基类指针
Shape* shape2 = new Rectangle(); // 声明派生类指针
// 调用基类成员函数 getWidth()
shape1->setWidth(5);
shape1->setHeight(7);
// 调用派生类成员函数 getWidth()
shape2->setWidth(5);
shape2->setHeight(7);
// 输出结果
cout << "Shape's area: " << shape1->area() << endl;
cout << "Rectangle's area: " << shape2->area() << endl;
return 0;
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C++之重载 重定义与重写用法详解 - Python技术站