Why the following programs will cause error? a) Program 1 .cpp #include <iostream> #include <string> using namespace std; C++ Programming– O.O.P Basics Iman Rasekh 39 class Box { int capacity; public: Box(int cap){ capacity = cap; } friend void show(); }; void Box::show() { Box b(10); cout<<"Value of capacity is: "<<b.capacity<<endl; } int main(){ show(); return 0; }
时间: 2024-01-14 20:02:50 浏览: 98
The following program will cause an error:
```c++
#include <iostream>
#include <string>
using namespace std;
class Box {
int capacity;
public:
Box(int cap){ capacity = cap; }
friend void show();
};
void Box::show() {
Box b(10);
cout<<"Value of capacity is: "<<b.capacity<<endl;
}
int main(){
show();
return 0;
}
```
This program will cause an error because the `show` function is defined as a friend function of the `Box` class, but it is not a member function of the `Box` class. Therefore, when the `show` function tries to access the `capacity` member variable of the `Box` class using an object of the `Box` class, it is not able to do so because the `capacity` variable is a private member of the `Box` class and can only be accessed by member functions of the `Box` class.
To fix this error, we can either make the `show` function a member function of the `Box` class, or we can pass an object of the `Box` class as a parameter to the `show` function so that it can access the private member variable through the object.
阅读全文