运营商<<无法访问班级的私人int

Operator<< cant access private int of class

本文关键字:lt int 访问 运营商      更新时间:2023-10-16

我尝试编译时会得到这个:

../monster.h:26:9:错误:‘int projectiv :: monster :: con'是私人

`int con;`
     ^

../monster.cpp:17:39:错误:在此上下文中

cout << "Constitution: " << monster.con << endl; ^

make:* [monster.o]错误1

据我了解,使运营商&lt;&lt;朋友应该允许它访问int con。我没有看到什么。

monster.h:

#ifndef MONSTER_H_
#define MONSTER_H_
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
#include <string>
using std::string;
namespace ProjectIV
{
  class Monster
  {
  friend ostream &operator<< (ostream &out, const Monster &monster);
  public:
    Monster(int con);
  private:
    int con;
  };
} /* namespace ProjectIV */
#endif /* MONSTER_H_ */

monster.cpp:

#include "Monster.h"
ostream &operator<< (ostream &out, const ProjectIV::Monster &monster)
{
  cout << "Constitution: " << monster.con << endl;
  return out;
}
ProjectIV::Monster::Monster(int con): con(con)
{}

main.cpp:

#include "Monster.h"
using namespace ProjectIV;
int main()
{
  Monster Gojira(140);
  cout << Gojira << endl;
  return 0;
}

this:

ostream& operator<<(ostream& out, const ProjectIV::Monster& monster)

应该是:

ostream& ProjectIV::operator<<(ostream& out, const ProjectIV::Monster& monster)

在这里您的不起作用示例,这是一个工作。


另外,根据Andreyt的评论,您应该在friend声明之前添加函数声明:

namespace ProjectIV {
    class Monster {
    friend ostream& operator<<(ostream& out, const Monster& monster);
    public:
        Monster(int con);
    private:
        int con;
    };
    ostream& operator<<(ostream& out, const Monster& monster);
    // ^^^ this
}

您的代码有两个问题。

首先,Monster类中的朋友声明是指ProjectIV::operator <<函数。ProjectIV::operator <<将成为Monster的朋友。您在Monster.cpp文件中定义的实际上是::operator <<。这是一个完全不同的功能,不是Monster的朋友。这就是为什么您会遇到错误的原因。

因此,您需要确定要结交朋友的功能 - 全局名称空间中的朋友或ProjectIV名称空间中的一个功能 - 并相应地行动。

如果要使operator <<成为ProjectIV名称空间的成员,则遇到第二个问题。朋友声明参考 封闭命名空间的成员,但他们没有将相应的声明引入封闭名称空间。在ProjectIV

中添加operator <<的声明仍然是您的责任。
namespace ProjectIV
{
  class Monster
  {
  friend ostream &operator<< (ostream &out, const Monster &monster);
  public:
    Monster(int con);
  private:
    int con;
  };
  ostream &operator<< (ostream &out, const Monster &monster);
} /* namespace ProjectIV */

然后将其定义为ProjectIV

的成员
ostream &ProjectIV::operator<< (ostream &out, const ProjectIV::Monster &monster)
{
  cout << "Constitution: " << monster.con << endl;
  return out;
}