EDIT:
The original program has multiple files as shown in here
I'm trying to access protected data member in my class from a friend member function of a different class.
I keep getting an access error:
9:32: error: invalid use of incomplete type 'class b' 5:7: error: forward declaration of 'class b' In member function 'void b::f(a*)': 12:13: error: 'int a::i' is protected 20:47: error: within this context
This is my code:
// Example program
#include <iostream>
#include <string>
class b;
class a{
public:
friend void b::f(a* pointer);
protected:
int i = 6;
};
class b{
public:
void f(a* pointer){std::cout<<pointer->a::i<<std::endl;}
};
int main()
{
a a1;
b b1;
b1.f(&a1);
}
The issue is only superficially related to friend
. It's rather due to circular dependencies of class definitions and member functions; a
needs to know the definition of b
because it refers to b::f
. But the definition of b::f
needs the definition of a
, as it refers to a::i
. Luckily, definitions of a class and its member functions can be separated from each other.
You can take the following measures to tackle this step by step:
class a;
class b { /* ... */ };
, but without defining its member functions (as they need access to a
's definition class a { /* ... */ };
, possibly with inline member function definitions b
's member functions.This is how it looks like:
// Step 1:
class a;
// Step 2:
class b{
public:
void f(a* pointer);
};
// Step 3:
class a{
public:
friend void b::f(a* pointer);
protected:
int i = 6;
};
// Step 4:
void b::f(a* pointer)
{
std::cout<<pointer->a::i<<std::endl;
}
At the point where you try to declare the method of b
a friend via friend void b::f(a* pointer);
, the class b
is incomplete. You cannot refer to members yet. On the other hand, b
only needs a forward declaration for a
:
// Example program
#include <iostream>
#include <string>
class a;
class b{
public:
void f(a* pointer);
};
class a{
public:
friend void b::f(a* pointer);
protected:
int i = 6;
};
void b::f(a* pointer){std::cout<<pointer->a::i<<std::endl;}
int main()
{
a a1;
b b1;
b1.f(&a1);
}
Try this. You are trying to reference b::f
before class b
is defined.
// Example program
#include <iostream>
#include <string>
class a;
class b{
public:
void f(a* pointer);
};
class a{
public:
friend void b::f(a* pointer);
protected:
int i = 6;
};
void b::f(a* pointer)
{std::cout<<pointer->a::i<<std::endl;}
int main()
{
a a1;
b b1;
b1.f(&a1);
}
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.