Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

friend for private class

Tags:

c++

friend

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?

like image 282
name Avatar asked May 13 '14 08:05

name


People also ask

Can a friend be private C++?

Friend function can be declared in any section of the class i.e. public or private or protected.

How do you declare a class friend?

Go to your friend's profile. Tap below their profile picture. Tap Edit Friend List then select Close friends. Tap Done.

What is the difference between friend and friend class?

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.

Are friend functions public or private?

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.


1 Answers

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.

like image 108
masoud Avatar answered Sep 21 '22 02:09

masoud