C++分文件编写时候多个类之间如何相互调用
时间: 2024-03-01 11:54:05 浏览: 36
在 C++ 分文件编写中,多个类之间相互调用的方法与单个类的调用方法类似。以下是一个简单的示例:
假设我们有两个类,一个是 Circle 类,用于计算圆的周长和面积;另一个是 Cylinder 类,用于计算圆柱的体积。我们可以将它们分别写在不同的文件中。
在 Circle 类的头文件 circle.h 中,我们需要声明计算圆周长和面积的函数:
```c++
#ifndef CIRCLE_H
#define CIRCLE_H
const double PI = 3.14159265358979323846;
class Circle {
public:
Circle(double radius);
double get_circumference() const;
double get_area() const;
private:
double radius_;
};
#endif /* CIRCLE_H */
```
在 Circle 类的实现文件 circle.cpp 中,我们需要定义这些函数:
```c++
#include "circle.h"
Circle::Circle(double radius) {
radius_ = radius;
}
double Circle::get_circumference() const {
return 2 * PI * radius_;
}
double Circle::get_area() const {
return PI * radius_ * radius_;
}
```
在 Cylinder 类的头文件 cylinder.h 中,我们需要包含 Circle 类的头文件 circle.h,并声明计算圆柱体积的函数:
```c++
#ifndef CYLINDER_H
#define CYLINDER_H
#include "circle.h"
class Cylinder {
public:
Cylinder(double radius, double height);
double get_volume() const;
private:
Circle base_;
double height_;
};
#endif /* CYLINDER_H */
```
在 Cylinder 类的实现文件 cylinder.cpp 中,我们需要定义这些函数:
```c++
#include "cylinder.h"
Cylinder::Cylinder(double radius, double height) : base_(radius), height_(height) {}
double Cylinder::get_volume() const {
return base_.get_area() * height_;
}
```
在 main.cpp 中,我们可以创建 Circle 和 Cylinder 对象,然后调用它们的函数:
```c++
#include "circle.h"
#include "cylinder.h"
int main() {
Circle circle(5.0);
Cylinder cylinder(5.0, 10.0);
double circumference = circle.get_circumference();
double area = circle.get_area();
double volume = cylinder.get_volume();
std::cout << "The circumference of the circle is: " << circumference << std::endl;
std::cout << "The area of the circle is: " << area << std::endl;
std::cout << "The volume of the cylinder is: " << volume << std::endl;
return 0;
}
```
通过以上示例,我们可以看出,多个类之间的相互调用方法与单个类的调用方法类似,只需要在头文件中包含其他类的头文件,并在类的构造函数和成员变量中使用其他类的对象即可。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)