如何在cpp文件中使用友元函数?

How to use a friend function in cpp file?

我有一个头文件和一个 cpp 文件...在 .h 文件中我声明了一个 ZZZ class 并添加了一些私有参数并声明了一个 friend 函数但是当我尝试访问 .cpp 文件中的私有参数时出现错误:

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

而且我在 heder 文件中也遇到了这个带有私有参数的错误:

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;
}

因为你在命名空间 XY 中声明了你的友元函数,你必须告诉编译器你在源文件中的定义属于已经声明的原型:

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

因此,要解决您的定义不是没有前向声明的新函数的歧义,您必须在源文件中使用名称空间作为前缀:

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

或者,作为另一种选择,您也可以执行以下操作:

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