Search code examples
c++namespacesfriend

How to use a friend function in cpp file?


I have a header file and a cpp file... In the .h file I declared a ZZZ class and added some private parameters and declared a friend function but when I try to access the private parametrs in the .cpp file I get an error:

error: within this context
     output << zzz.ZZZ_name << "." ;

And I get also in the heder file this error with the private parametrs:

error: 'std::string X::Y::ZZZ::ZZZ_name' is private
     string ZZZ_name;

ZZZ.h

#include <iostream>
#include <string>
using std::string;

namespace X {
namespace Y {

class ZZZ {
private:
    string ZZZ_name;

public:
    friend std::ostream &operator<<(std::ostream &output, const ZZZ &zzz);
};

std::ostream &operator<<(std::ostream &output, const ZZZ &zzz);

}}

ZZZ.cpp

#include "ZZZ.h"
#include <stdbool.h>

using namespace X::Y;
using std::cout;

std::ostream& operator<<(std::ostream& output, const ZZZ& zzz){
    output << zzz.ZZZ_name << "." ;
    return output;
}

Solution

  • Because you are declared your friend function inside namespaces X and Y, you have to tell the compiler that your definition in the source file belongs to the already declared prototype:

    std::ostream& operator<<(std::ostream& output, const ZZZ& zzz);
    

    So, to resolve ambiguity that your definition is not a new function without a forward declaration, you have to prefix it with namespaces inside the source file:

    std::ostream& X::Y::operator<<(std::ostream& output, const ZZZ& zzz) {
        output << zzz.ZZZ_name << "." ;
        return output;
    }
    

    Or, as another option, you can do the following as well:

    namespace X { namespace Y {
        std::ostream& operator<<(std::ostream& output, const ZZZ& zzz) {
            output << zzz.ZZZ_name << "." ;
            return output;
        }
    }}