我无法捕捉到这个错误,它一定很容易。我有一个头文件(snim.h):
#ifndef SNIM_CLASS_HH_
#define SNIM_CLASS_HH_
#include <iostream>
namespace snim {
class SnimModel {
int communitySize; // Total size of the community
public:
SnimModel(int c) : communitySize(c) {};
friend std::ostream& operator<<(std::ostream&, const SnimModel&);
};
} /* end namespace */
#endif
Run Code Online (Sandbox Code Playgroud)
和一个实现文件:
#include "snim.h"
using namespace snim;
std::ostream& operator<<(std::ostream& os, const SnimModel& s) {
os << "[Total Size]\n[";
os << s.communitySize << "]\n";
return os;
};
Run Code Online (Sandbox Code Playgroud)
因此,当我尝试编译它时
In function ‘std::ostream& operator<<(std::ostream&, const snim::SnimModel&)’:
snim.cpp:9:11: error: ‘int snim::SnimModel::communitySize’ is private within this context
os << s.communitySize << "]\n";
Run Code Online (Sandbox Code Playgroud)
您在全局命名空间中定义了另一个操作符,它应该在 namespace snim
std::ostream& snim::operator<<(std::ostream& os, const SnimModel& s)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者
namespace snim
{
std::ostream& operator<<(std::ostream& os, const SnimModel& s)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)