我有一个头文件和一个cpp文件...在.h文件中我声明了一个ZZZ
类并添加了一些私有参数并声明了friend
函数但是当我尝试访问.cpp文件中的私有参数我收到错误:
error: within this context
output << zzz.ZZZ_name << "." ;
我还在私人参数中发现了这个错误:
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;
}
答案 0 :(得分:-2)
因为你在名称空间X
和Y
中声明了你的朋友函数,你必须告诉编译器你在源文件中的定义属于已经声明的原型:
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;
}
}}