Why the following programs will cause error? #include <iostream> #include <string> using namespace std; class B { int b; public: B(){} B(int i){ b = i; } int show(){ return b; } }; class C { B b; public: C(int i){ b = B(i); } friend void show(){ C c(10); cout<<"value of b is: "<<c.b.show()<<endl; } }; int main(){ C c(1); c.show(); return 0; }
时间: 2024-01-14 14:02:58 浏览: 26
The program will cause an error because the `show()` function is defined as a friend function of the `C` class, but it tries to access the private member `b` of the `C` class through the `b.show()` method call.
To fix it, you can change the `show()` function to a member function of the `C` class, and then access the private member `b` directly using the `.` operator. Here's the corrected code:
```
#include <iostream>
#include <string>
using namespace std;
class B {
int b;
public:
B() {}
B(int i) { b = i; }
int show() { return b; }
};
class C {
B b;
public:
C(int i) { b = B(i); }
void show() {
cout<<"value of b is: "<<b.show()<<endl;
}
};
int main() {
C c(1);
c.show();
return 0;
}
```
Alternatively, you can keep the `show()` function as a friend function of the `C` class, but change the `b.show()` method call to `c.b.show()`, like this:
```
#include <iostream>
#include <string>
using namespace std;
class B {
int b;
public:
B() {}
B(int i) { b = i; }
int show() { return b; }
};
class C {
B b;
public:
C(int i) { b = B(i); }
friend void show() {
C c(10);
cout<<"value of b is: "<<c.b.show()<<endl;
}
};
int main() {
show();
return 0;
}
```