介绍
在本实验中,我们将演示如何创建一个展示层次继承(Hierarchical Inheritance)概念的 C++ 程序。我们将通过编写一个使用类和对象的简单程序来更好地理解这一主题。
在本实验中,我们将演示如何创建一个展示层次继承(Hierarchical Inheritance)概念的 C++ 程序。我们将通过编写一个使用类和对象的简单程序来更好地理解这一主题。
main.cpp
我们将在 ~/project
目录下使用以下命令创建一个名为 main.cpp
的新文件:
touch ~/project/main.cpp
Shape
类我们需要做的第一件事是定义 Shape
类,它将作为 Rectangle
和 Triangle
类的父类。在这个类中,我们将创建两个受保护的成员变量 width
和 height
,用于存储形状的宽度和高度。
然后,我们将创建一个公共成员函数 setDimensions
,用于设置这些尺寸并在控制台上打印一条消息。
以下是应添加到 main.cpp
中的 Shape
类的代码块:
#include <iostream>
using namespace std;
class Shape {
//protected member variables are only accessible within the class and its descendant classes
protected:
float width, height;
//public members are accessible everywhere
public:
void setDimensions(float w, float h) {
cout << "Setting the Dimensions using the parent Class: Shape\n";
cout << "The dimensions are: " << w << " and " << h << "\n\n";
width = w;
height = h;
}
};
Rectangle
类接下来,我们将创建继承自 Shape
类的 Rectangle
类。在这里,我们将使用方法重写(Method Overriding)技术,通过 area()
函数计算矩形的面积。
以下是应添加到 main.cpp
中的 Rectangle
类的代码块:
class Rectangle: public Shape {
//Method Overriding
public:
float area() {
return (width * height);
}
};
Triangle
类现在,让我们创建同样继承自 Shape
类的 Triangle
类。在这里,我们将使用方法重写(Method Overriding)技术,通过 area()
函数计算三角形的面积。
以下是应添加到 main.cpp
中的 Triangle
类的代码块:
class Triangle: public Shape {
//Method Overriding
public:
float area() {
return (width * height / 2);
}
};
main()
函数现在,是时候编写 main()
函数了。在这里,我们将为 Rectangle
和 Triangle
类创建对象,并设置它们的尺寸。
然后,我们将使用 area()
函数通过各自的对象计算 Rectangle
和 Triangle
的面积。
以下是应添加到 main.cpp
中的 main()
函数的代码块:
int main() {
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << "===== Program to demonstrate the concept of Hierarchical Inheritance in CPP =====\n\n";
//Declaring the Class objects to access the class members
Rectangle rectangle;
Triangle triangle;
rectangle.setDimensions(5, 3);
triangle.setDimensions(2, 5);
cout << "\nArea of the Rectangle computed using Rectangle Class is : " << rectangle.area() << "\n\n\n";
cout << "Area of the Triangle computed using Triangle Class is: " << triangle.area();
cout << "\n\n\n";
return 0;
}
要在终端中执行程序,首先导航到 ~/project
目录。然后输入以下命令来编译 main.cpp
文件:
g++ main.cpp -o main
之后,使用以下命令运行程序:
./main
你应该会在终端中看到输出结果。
在本实验中,我们学习了如何在 C++ 中演示层次继承(Hierarchical Inheritance)的概念。我们创建了 Shape
类,它是 Rectangle
和 Triangle
的父类。然后,我们为每个子类创建了对象,并通过方法重写(Method Overriding)计算了矩形和三角形的面积。
希望本实验能帮助你更好地理解 C++ 中层次继承的工作原理。如果有任何疑问,欢迎通过下方的评论区联系我们。