作为朋友的C ++重载ostream运算符会导致错误:变量在此上下文中是私有的

时间:2017-02-09 17:59:35

标签: c++

我无法捕捉到这个错误,它一定很容易。我有一个头文件(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

和实施文件:

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

因此,当我尝试编译它时,

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

1 个答案:

答案 0 :(得分:4)

您在全局命名空间中定义了另一个运算符,它应该在namespace snim

std::ostream& snim::operator<<(std::ostream& os, const SnimModel& s)
{
    // ...
}

namespace snim
{
    std::ostream& operator<<(std::ostream& os, const SnimModel& s)
    {
        // ...
    }
}

Demo