运营商<<无法访问班级的私人int
Operator<< cant access private int of class
我尝试编译时会得到这个:
../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;
}
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 呼叫运营商<<临时
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- 运营商&lt;&lt;无法访问班级的私人int
- std::pair的默认构造函数<>将基本类型(int等)设置为零
- 如何显示/打印字符串对象?cout & lt; & lt;Int工作,count <<字符串