面试题答案
一键面试函数重载
- 描述:函数重载是指在同一作用域内,可以有多个同名函数,但这些函数的参数列表(参数个数、参数类型或参数顺序)必须不同。编译器会根据调用函数时提供的参数来决定调用哪个函数版本,这是一种编译时多态。
- 举例:
#include <iostream>
// 函数重载示例
void print(int num) {
std::cout << "打印整数: " << num << std::endl;
}
void print(double num) {
std::cout << "打印双精度浮点数: " << num << std::endl;
}
int main() {
print(5);
print(3.14);
return 0;
}
虚函数/函数重写
- 描述:虚函数是在基类中使用
virtual
关键字声明的成员函数,它允许派生类提供该函数的不同实现,即函数重写。当通过基类指针或引用调用虚函数时,实际调用的是派生类中重写的函数版本,这就是运行时多态。 - 举例:
#include <iostream>
#include <cmath>
// 图形基类
class Shape {
public:
virtual double area() const {
return 0.0;
}
};
// 圆形类,继承自Shape
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return M_PI * radius * radius;
}
};
// 矩形类,继承自Shape
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
};
int main() {
Shape* shapes[2];
shapes[0] = new Circle(5.0);
shapes[1] = new Rectangle(4.0, 3.0);
for (int i = 0; i < 2; ++i) {
std::cout << "图形面积: " << shapes[i]->area() << std::endl;
delete shapes[i];
}
return 0;
}
在上述图形类继承体系的例子中,Shape
类中的 area
函数被声明为虚函数,Circle
和 Rectangle
类重写了该虚函数。在 main
函数中,通过 Shape
类型的指针数组来存储不同派生类对象的指针,当调用 area
函数时,根据实际指向的对象类型(圆形或矩形),调用相应派生类中重写的 area
函数版本,从而实现运行时多态。