c++ 实现圆柱类 包含友元函数的封闭类
时间: 2023-05-22 08:00:58 浏览: 107
好的,以下是一个实现圆柱类的封闭类,其中包含一个友元函数:
```c++
#include <iostream>
using namespace std;
class Cylinder {
private:
double radius;
double height;
public:
Cylinder(double r, double h) {
radius = r;
height = h;
}
double getVolume() {
return 3.14 * radius * radius * height;
}
friend void printVolume(Cylinder c);
};
void printVolume(Cylinder c) {
cout << "The volume of the cylinder is: " << c.getVolume() << endl;
}
int main() {
Cylinder c(2, 5);
printVolume(c);
return 0;
}
```
友元函数 `printVolume` 可以访问 `Cylinder` 类的私有成员变量 `radius` 和 `height`,并计算出圆柱的体积。在 `main` 函数中,我们创建了一个 `Cylinder` 对象 `c`,并调用 `printVolume` 函数打印出圆柱的体积。
相关问题
c++定义一个圆柱类用友元函数计算面积和体积
以下是一个圆柱类的定义,其中包括了计算面积和体积的友元函数:
```c++
#include <iostream>
using namespace std;
class Cylinder {
private:
double radius; // 圆柱的底面半径
double height; // 圆柱的高度
public:
Cylinder(double r = 0, double h = 0) : radius(r), height(h) {}
friend double area(const Cylinder& c); // 友元函数,用于计算圆柱的表面积
friend double volume(const Cylinder& c); // 友元函数,用于计算圆柱的体积
};
double area(const Cylinder& c) {
double area_bottom = c.radius * c.radius * 3.14159;
double area_side = 2 * c.radius * 3.14159 * c.height;
return 2 * area_bottom + area_side;
}
double volume(const Cylinder& c) {
return c.radius * c.radius * 3.14159 * c.height;
}
int main() {
Cylinder c(2, 5);
cout << "Area: " << area(c) << endl;
cout << "Volume: " << volume(c) << endl;
return 0;
}
```
在这个例子中,我们定义了一个名为 `Cylinder` 的类,其中包括了圆柱的底面半径和高度。然后,我们定义了两个友元函数 `area` 和 `volume`,它们分别用于计算圆柱的表面积和体积。这两个函数都接受一个 `const Cylinder&` 类型的参数,即一个圆柱对象的引用,用于获取圆柱的底面半径和高度。在 `main` 函数中,我们创建了一个半径为 2、高度为 5 的圆柱对象,并分别调用了 `area` 和 `volume` 函数来计算其表面积和体积。
c++类模板中的友元函数
C++类模板中的友元函数与非模板类的友元函数类似,可以访问类的私有成员和保护成员。但是,模板类的友元函数需要在函数名前加上 `template <typename T>`,其中 `T` 是模板参数的占位符,表示该友元函数是一个模板函数。
例如,定义一个模板类 `MyClass`,并声明一个友元函数 `template <typename T> void myFunc(MyClass<T>& obj)`,其中 `T` 是模板参数。在函数体中,可以直接访问 `MyClass` 的私有成员和保护成员,例如:
```cpp
template <typename T>
class MyClass {
private:
T data;
public:
friend void myFunc<>(MyClass<T>& obj);
};
template <typename T>
void myFunc(MyClass<T>& obj) {
obj.data = T(); // 访问 MyClass 的私有成员
}
```
需要注意的是,在模板类中声明友元函数时,需要在类外显式实例化该函数模板,例如:
```cpp
template void myFunc<int>(MyClass<int>& obj);
```
这样才能保证编译器能够正确地匹配模板参数。