A.hpp
class A
{
public:
class B
{
int x;
public:
B(int f);
};
void alpha(B *random);
};
A.cpp
void A::alpha(A::B *random)
{
// access x here, how to do it?
}
The private variable is getting set at some place and I want to access that value in this alpha
function. How can I access x
inside alpha()
?
EDIT: 2nd Question: A.hpp
class A
{
public:
class B
{
int x;
public:
B(int f);
};
virtual void alpha(B *random) = 0;
};
C.hpp
class C : public A
{
public:
virtual void alpha(B *random);
};
C.cpp
void C::alpha(A:B *random)
{
// access x here, how to do it?
}
You can make class A
a "friend" of class B
which allows A
to access private members of B
combining your files for ease of compilation:
class A
{
public:
class B
{
friend class A; // *** HERE ***
int x;
public:
B(int f);
};
void alpha(B *random);
};
void A::alpha(B *random)
{
int x = random->x;
}
int main() {}
A class can access another class's private
members if it's a friend
of that other class, like in this example:
class A {
public:
class B {
friend class A;
int x;
public:
B(int f);
};
void alpha(B *random) { random->x = 10; }
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.