How to define friend for private classes?
#include <iostream>
class Base_t{
private:
struct Priv_t{
friend std::ostream & operator<<(std::ostream &os, const Priv_t& obj);
} p;
friend std::ostream & operator<<(std::ostream &os, const Base_t& obj);
};
std::ostream & operator<<(std::ostream &os, const Base_t& obj) {
return os << "base: " << obj.p;
}
std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj) {
return os << "priv";
}
int main() {
Base_t b;
std::cout << b << std::endl;
}
error:
:!make t17 |& tee /tmp/vB5G5ID/54
g++ t17.cpp -o t17
t17.cpp: In function 'std::ostream& operator<<(std::ostream&, const Base_t::Priv_t&)':
t17.cpp:5:16: error: 'struct Base_t::Priv_t' is private
struct Priv_t{
^
t17.cpp:15:59: error: within this context
std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj) {
^
make: *** [t17] Error 1
shell returned 2
It works when I define friend directly in Priv_t
friend std::ostream & operator<<(std::ostream &os, const Priv_t& obj) { return os << "priv"; }
How to do that outside class/struct definition?
Friend function can be declared in any section of the class i.e. public or private or protected.
Go to your friend's profile. Tap below their profile picture. Tap Edit Friend List then select Close friends. Tap Done.
It is a class that is used with 'friend' keyword. It is not necessary to declare it before using it. A friend class is used when a class is created as an inherited class from another base class. It is used to access private and protected members of the class.
The friend function can be a member of another class or a function that is outside the scope of the class. A friend function can be declared in the private or public part of a class without changing its meaning. Friend functions are not called using objects of the class because they are not within the class's scope.
While Priv_t
is a private declaration, you should move
friend std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj);
into the Base_t
:
class Base_t
{
private:
struct Priv_t
{
} p;
friend std::ostream & operator<<(std::ostream &os, const Base_t& obj);
friend std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj);
};
Live code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With