基类函数的例子
时间: 2023-09-12 14:07:33 浏览: 41
基类函数(也称为虚函数)是在基类中声明的函数,可以在派生类中重写。这种方法允许在派生类中定义特定于该类的行为,同时仍然保留与基类相同的接口。
以下是一个基类函数的例子:
```c++
class Shape {
protected:
int width, height;
public:
Shape(int w = 0, int h = 0) {
width = w;
height = h;
}
// 声明一个虚函数
virtual int area() {
cout << "Parent class area :" << endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle(int w = 0, int h = 0):Shape(w, h) { }
// 重写基类的虚函数
int area() {
cout << "Rectangle class area :" << endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle(int w = 0, int h = 0):Shape(w, h) { }
// 重写基类的虚函数
int area() {
cout << "Triangle class area :" << endl;
return (width * height / 2);
}
};
int main() {
Shape *shape;
Rectangle rec(10, 7);
Triangle tri(10, 5);
// 存储矩形的地址
shape = &rec;
// 调用矩形的函数 area
shape->area();
// 存储三角形的地址
shape = &tri;
// 调用三角形的函数 area
shape->area();
return 0;
}
```
在这个例子中,Shape 是一个基类,而 Rectangle 和 Triangle 都是派生类。Shape 类中声明了一个虚函数 area(),这意味着可以在派生类中重写该函数。Rectangle 和 Triangle 类都重写了该函数,并在其中定义了特定于该类的行为。
在主函数中,通过将 Rectangle 和 Triangle 的地址分配给 Shape 指针变量,可以调用各自的 area() 函数。由于 area() 是一个虚函数,因此将调用适当的派生类的函数,而不是基类的函数。