Question

David Hagood david.hagood@gmail.com
Sun Oct 12 12:54:00 GMT 2014


On 10/07/2014 08:57 AM, Graziano Servizi wrote:
> So, if I have well understood I could write such a short code:
>
> # include <iostream>
>
> class P
>   {
>    friend void friend_inline()
>     {std :: cout << P :: Name << ' ' << p << '\n';}
    You will need to qualify "p" as well:
    {std :: cout << P::Name << ' ' << P::p << '\n';}
>    static constexpr int Name = 20;
>    static constexpr double p = 12.5;
>
>    };
>
> int main()
>   {
>    P p;
>    // how can I call friend_inline ?
      friend_inline();
> }
It's just a function.

It's probably more clear if you split the definition of the function, 
the declaration of it being a friend, and the implementation:

// Declaration: there exists a function named "friend_inline"...
void friend_inline();

// Class declaration.
class P
  {
   // Class P allows a non-class function "friend_inline" to access its 
private variables...
   friend void friend_inline();
   static constexpr int Name = 20;
   static constexpr double p = 12.5;

   };

// Definition of the function "friend_inline"
void friend_inline()
{
   std::cout << P::Name << ' ' << P::p << std::endl;
}

Each of these things - declaration, friending, and definition - are 
separate things. They can be combined into one statement (as in your 
example) for brevity, but they still are 3 different things.

Also: be VERY CAREFUL about using friend - it's almost always a bad 
idea. You are almost always better off making one or more public member 
functions, and calling them, than you are exposing every last private 
member to a non-member function.

somewhat OT: I wouldn't put spaces between the class name, the colon, 
and the variable name in your code; they are all one thing - the name of 
the object being accessed. Also, use "std::endl" to end a sequence of 
insertions to a stream, not just '\n' - std::endl has more semantic 
meaning to the system, it really means "I am done with this line, do 
whatever you need to do, such as flushing it to the file", vs. "\n" 
which just means "insert a newline character".




More information about the Gcc-help mailing list