J
Jess
Hello,
I am trying to define a friend function for my class as follows:
#include<iostream>
using namespace std;
class B;
class A{
friend void B::g(const A&);
//friend class B;
private:
int x;
public:
A(int a):x(a){}
};
class Bublic A{
public:
B(int a):A(a){}
void g(const A& a){cout << a.x << endl;}
};
However, this failed with compiler error saying A::x is private and
member B::g is declared before type B is defined. This is surprising
because I've given forward declaration for B. I also declared B::g as
a friend, and so I think it should be able to access A::x. What is
going wrong here?
I then tried to replace friend void B::g(const A&) with friend class B
and then it worked. However, I'd only like B's g method to access A's
private part, not the whole B class. Is there a solution for my
problem?
Thanks,
Jess
I am trying to define a friend function for my class as follows:
#include<iostream>
using namespace std;
class B;
class A{
friend void B::g(const A&);
//friend class B;
private:
int x;
public:
A(int a):x(a){}
};
class Bublic A{
public:
B(int a):A(a){}
void g(const A& a){cout << a.x << endl;}
};
However, this failed with compiler error saying A::x is private and
member B::g is declared before type B is defined. This is surprising
because I've given forward declaration for B. I also declared B::g as
a friend, and so I think it should be able to access A::x. What is
going wrong here?
I then tried to replace friend void B::g(const A&) with friend class B
and then it worked. However, I'd only like B's g method to access A's
private part, not the whole B class. Is there a solution for my
problem?
Thanks,
Jess