【问题标题】:compiler error when declaring constructor function声明构造函数时编译器错误
【发布时间】:2012-07-25 21:05:20
【问题描述】:

我正在开发我的严肃 C++ 程序。我已经有一段时间没有上课了,所以我有点生疏了。在开始游戏循环的基本实现时(在花费了永远让 SFML 工作之后),我不断遇到问题。一段时间后,我在尝试定义构造函数时将问题列表归结为错误。尝试编译时出现以下错误。

1>game.obj : 错误 LNK2005: "public: __thiscall game::game(void)" (??0game@@QAE@XZ) 已在 main.obj 中定义

1>game.obj : 错误 LNK2005: "public: void __thiscall game::gameLoop(void)" (?gameLoop@game@@QAEXXZ) 已经定义在 main.obj

我在 main 中的代码是

#include <SFML/Graphics.hpp>

#include "game.cpp"

int main()
{
    return 0;
}

在game.h中

#ifndef _game_h
#define _game_h

class game
{
public:
     game();
    void gameLoop();
};

#endif

在 game.cpp 中是

#include <iostream>
#include "game.h"

game::game()
{
    std::cout << "Constructed thingie";
}

void game::gameLoop()
{
    std::cout << "RAN LOOP!" << std::endl;
}

我不知道为什么会遇到这个错误。任何帮助都会很好,因为我想开始我的项目。

【问题讨论】:

  • 不要在 main 中包含 .cpp

标签: c++ constructor visual-c++-2008


【解决方案1】:

您应该在 main 中包含 #include "game.h",而不是 game.cpp

【讨论】:

  • 这只会导致 game.cpp 不知道类游戏是什么。即使我在 game.h 中包含了 game.cpp 也不知道这应该如何帮助任何事情。 --编辑-- 没关系。在 main 和 game.cpp 中包含 game.h 会因为某种原因编译。
  • 我认为你看错了,你不应该从 game.cpp 中删除 game.h,只需将 main 中的 game.cpp 替换为 game.h
  • 是的,它奏效了。我只是把它误读为“将game.h的包含移到main.cpp”而不是“在main.cpp中包含game.h,而不是game.cpp”。它现在工作正常:) 不知道如何结束这个问题。
猜你喜欢
  • 1970-01-01
  • 2014-08-09
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
  • 2020-06-06
相关资源
最近更新 更多