Hello!
Please, classes A and B are friends!
Please, where is the mistake, why is another class not seing elements from class b, if it is its friend? A should see b. Many thanks!
class B {
friendclass A; // A sees into the B class
private:
int i;
B(int c): i(c) {}
};
class A {
public:
void a(B b);
};
void A::a(B b){
b.i=10;
}
int main(){
B obj1(2);
B obj2(3);
B obj3(4);
int z;
z=obj1.i;
cout<<z<<endl;
return 0;
}
Hello!
Please, what is the way to solve it? (except turning B constructor to public?
The point of the example is to show what friend class sees, if I turn B constructor to public, it is not a good example to show what friend classes do!
class B {
friendclass A; // A sees into the B class
private:
int i;
};
class A {
public:
A(int);
void a(B b);
};
A::A(int c):i(c){};
void A::a(B b){
b.i=10;
}
int main(){
B obj1(2);
B obj2(3);
B obj3(4);
int z;
z=obj1.i;
cout<<z<<endl;
re
Compiler says: Line 19: error: class 'A' does not have any field named 'i'
(A really does not, but B does and it is friend to B and can see into it, can't it???)
(Do I probably have to give it a virtual object as parameter too and how to sintax it???)
Hello!
Yes ,Iknow it all, but the code I wrote does not work, so I wonder how to "fix" the code.
I moved the constructor from B to A, there is obvioulsy sth missing...sth that will "tell" A that it "can" see into B, and this "something" is sth MORE then just declaring A as B's friend in the line2...
class B {
friendclass A; // A sees into the B class
private:
int i;
};
class A {
public:
A(int);
void a(A b);
};
A::A(int c):i(c){}; //.cpp: In constructor 'A::A(int)':
//Line 19: error: class 'A' does not have any field named 'i'
void A::a(A b){
b.i=10;
}
int main(){
A obj1(2);
A obj2(3);
A obj3(4);
int z;
z=obj1.i;
cout<<z<<endl;
return 0;
}
#include <iostream>
class B
{
friendclass A;
private:
B(int c) : i(c) {}
int i;
};
class A
{
public:
void a()
{
B b(10);
std::cout << b.i << std::endl;
}
};
int main()
{
A a;
a.a();
}