C++ C++;“成员”;粉碎:粉碎“;不是类型名。

C++ C++;“成员”;粉碎:粉碎“;不是类型名。,c++,object,constructor,reference,C++,Object,Constructor,Reference,我需要将对象的引用传递给构造函数。我在构造函数中传递一个引用,但它给出了以下错误:成员“Smash::Smash”不是类型名 Smash.h: #pragma once #include "Smash.h" #include "Window.h" #include "Input.h" #include "Game.h" #include "Render.h" class Smash { public: Smash & smash; Game game(smash); }

我需要将对象的引用传递给构造函数。我在构造函数中传递一个引用,但它给出了以下错误:成员“Smash::Smash”不是类型名

Smash.h:

#pragma once
#include "Smash.h"
#include "Window.h"
#include "Input.h"
#include "Game.h"
#include "Render.h"

class Smash {
public:
    Smash & smash;
    Game game(smash);
};
例如,下面是类游戏的构造函数声明:

#pragma once
#include "Smash.h"

class Game {
    public:
        Smash smash;
        Game(Smash & obj); //obj IS THE smash OBJECT
};
我不明白。该参数是一个引用,也是一个smash对象。
提前感谢。

您有一个循环依赖关系。“扣杀。h包括比赛。h包括扣杀。h包括比赛。h”

这是行不通的

#pragma once
将使其实际为“Smash.h包含Game.h”或“Game.h包含Smash.h”(取决于.cpp文件中首先包含的是哪个),但这两个头确实都需要在另一个头中找到声明


您必须使用前向声明来删除至少一个方向上的依赖项。

您必须正确地使用
pragma一次
,以避免在相互依赖的标题中无休止地循环。然而,这是不够的。您还应该在
smash.h

但是,还有一些其他问题使您的示例更难找到工作:

  • 首先,您的
    Smash
    类有一个成员,该成员是对
    Smash
    的引用。这意味着您还必须定义初始化此引用的构造函数

  • 其次,您对member
    game()
    的声明没有为参数使用有效的类型(键入?)。如果
    game()
    与调用该参数的Smash对象一起工作,则可以通过删除该参数来纠正此问题

  • 第三,如果需要
    game()
    Smash s
    参数,则需要定义一个函数,该函数按值接受参数
    Smash
    。然后还需要一个复制构造函数

将这一切包装在一起,您将得到
smash.h

#pragma once
#include "Game.h"

class Game;             // Forward declaration for breaking the circular issue
class Smash {
public:
    Smash & smash;      // ==> needs to be initailized at construction
    Smash();            // <== therefore needs a constructor
    Game game(Smash s); // <== parameter needs a valid type
    Smash(const Smash &s);  // <== needs a copy constructor for param passing by value
};
#pragma一次
#包括“Game.h”
班级游戏;//打破循环问题的前瞻性声明
班级扣杀{
公众:
Smash&Smash;//=>需要在构造时初始化

粉碎;//你的?
Game.h
包括
Smash.h
Smash.h
包括
Game.h
,你有一个循环依赖项。其中一个需要更改为只包括一个类声明,但很难说是哪一个,而不知道你对这些类型做了什么。@Praetorian:不是答案ionAnd
Smash.h
也包括它自己:)这里的另一个问题是
Game(Smash)
不是一个成员变量声明。@Praetorian你知道在哪里做这些前向声明吗?@PythonLover17不,不是没有。(Lightness在他的第一个评论中已经问过你一个)