Consider the following class. Add a friend fuction to this class that shows the capacity. .cpp class Box { int capacity; public: Box(int cap){ capacity = cap; }
时间: 2024-02-13 16:06:34 浏览: 27
Sure, here's an example of how you could add a friend function to the `Box` class that shows the capacity:
```cpp
class Box {
int capacity;
public:
Box(int cap) {
capacity = cap;
}
friend void showCapacity(Box box);
};
void showCapacity(Box box) {
std::cout << "The capacity of the box is: " << box.capacity << std::endl;
}
```
In this example, we declare the `showCapacity` function as a friend of the `Box` class using the `friend` keyword. This allows the `showCapacity` function to access the private member variable `capacity` of the `Box` class.
The `showCapacity` function takes a `Box` object as a parameter and simply prints out the capacity of the box using `std::cout`. You can call this function like this:
```cpp
Box myBox(10);
showCapacity(myBox); // Output: The capacity of the box is: 10
```