c++ - 错误消息:嵌套名称说明符中的类型不完整

标签 c++ forward-declaration

我知道有很多类似的命名问题,但是在阅读了许多问题后我无法弄清楚我的问题。

我正在为一个类项目编写游戏。

class Dungeon中,function monsterTurn()需要访问被声明为setCurrSp()保护的class Hero。因此,我尝试将monsterTurn()作为 friend 功能添加到Hero。因为我在#include "Hero.hpp"中有class Dungeon,所以我使用了前向声明,但是它抛出了一个错误Incomplete type 'Dungeon' named in nested name specifier

我知道将setCurrSp()声明为public可以解决所有这些问题,但是让setter公开是不好的。似乎打开后门以进行意外的修改。如果我做错了,请纠正我。

以下是部分代码。

英雄

#include <stdio.h>
#include <iostream>
#include <sstream>
#include <vector>
#include "Entity.hpp"
class Dungeon;

class Hero : public Entity{

protected:
    void setCurrSp(int currSp)              { this->currSp = currSp;}
public:
    friend void Dungeon::monstersTurn(vector<Hero>::iterator hero, vector<Hero> heros);
}

地牢
#include <stdio.h>
#include <vector>
#include "Hero.hpp"
#include "Monster.hpp"
class Dungeon{
public:
    void monstersTurn(vector<Hero>::iterator hero, vector<Hero> heroes);
}

任何帮助将不胜感激。

最佳答案

对于friend声明

    friend void Dungeon::monstersTurn(vector<Hero>::iterator hero, vector<Hero> heros);

前向声明(forward declaration)
class Dungeon;

还不够。

演示:
class Dungeon; // forward declaration

class Hero {
  friend void Dungeon::takeHero(Hero&);
};

class Dungeon {
  public:
    void take(Hero&);
};

输出:

main.cpp:5:38: error: invalid use of incomplete type 'class Dungeon'
    4 |   friend void Dungeon::takeHero(Hero&);
      |                                      ^
main.cpp:1:7: note: forward declaration of 'class Dungeon'
    1 | class Dungeon; // forward declaration
      |       ^~~~~~~

Live Demo on coliru
class Hero需要一个完整的class Dungeon声明才能“知道”其成员。

对于friend class声明,向前声明就足够了:
class Dungeon; // forward declaration

class Hero {
  friend class Dungeon;
};

class Dungeon {
  public:
    void take(Hero&);
};

输出:

(无)–编译无投诉

Live Demo on coliru

关于c++ - 错误消息:嵌套名称说明符中的类型不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61452237/

相关文章:

c++ - 模板类相互使用会产生歧义错误

c++ - 将类前向声明​​为模板参数

c++ - 在另一个文件 C++ 中转发声明

c++ - 256如何存储在char变量和unsigned char中

c++ - Project1.exe 中 0x00007FFCA550A839 处的未处理异常:Microsoft C++ 异常:内存位置 0x0000002F82CFEF60 处的 std::bad_alloc。发生

c++ - 在一个线程中通过 tcp socket 发送和接收数据

c++ - 这个 # 在 C++ 中的函数参数中意味着什么

c++ - 为什么我的指针会导致段错误?

function - MATLAB 是否支持前向声明?

c++ - 表示元素列表的 smth 的前向声明