gpt4 book ai didi

C++ 成员 "Smash::smash"不是类型名称。

转载 作者:行者123 更新时间:2023-11-28 02:15:58 25 4
gpt4 key购买 nike

我需要将对象的引用传递给构造函数。我在构造函数中传递了一个引用,但它给出了这个错误:Member "Smash::smash"is not a type name.

粉碎.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);
};

例如,这里是类 Game 的构造函数声明:

#pragma once
#include "Smash.h"

class Game {
public:
Smash smash;
Game(Smash & obj); //obj IS THE smash OBJECT
};

我不明白。该参数是一个引用,也是粉碎对象。提前致谢。

最佳答案

您已经正确地使用了 pragma once 来避免在相互依赖的 header 中无休止地循环。然而,这还不够。您还应该在 smash.h

中添加对 Game 的前向引用

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

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

  • 其次,您的成员 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
};

另一个标题没问题。

MSVC2015 的有趣注意事项:如果缺少前向声明,出于奇怪的原因,编译器会在 game() 的定义上报告错误 3646。这是一种误导,因为此错误代码与覆盖相关,而覆盖与真正的问题根本无关。

关于C++ 成员 "Smash::smash"不是类型名称。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com