c++ - 错误 : Class computer comp is already defined in computer. 对象

标签 c++ lnk2005

我目前正在玩 C++,并试图重建我用 C++ 制作的 Tic Tac Toe 批处理控制台游戏,但碰壁了,我无法弄清楚如何摆脱错误 TicTacToe.obj : error LNK2005: “class computer comp” (?comp@@3Vcomputer@@A) 已经在 computer.obj 中定义。我曾尝试从 header 中删除函数 computer 的声明,以及 C++ 中函数的定义,但这并没有解决错误。我想出如何删除此错误的唯一方法是删除对象名称,我有点不想这样做。我使用了网站上给出的示例 http://www.cplusplus.com/doc/tutorial/classes/设置类(class)计算机。您可以就我目前遇到的任何错误或我可能不需要的任何函数提供的任何信息都非常欢迎,因为我想了解更多有关 C++ 的信息。

代码:

井字游戏.cpp

// TicTacToe.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include "computer.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    comp.Select();
    Sleep(1000);
}

计算机.cpp

#include "stdafx.h"
#include "computer.h"
#include <iostream>
using namespace std;

computer::computer()
{
}

computer::~computer()
{
}

void computer::Select()
{
}

计算机.h

#pragma once
class computer
{
public:
    computer();
    ~computer();
    void Select(void);
} comp;

额外信息:

我在运行 Windows 7 的笔记本电脑上使用 Microsoft Visual Studio Professional 2013。

最佳答案

因为您在两个模块 computer.cppTicTacToe.cpp 中包含 header "computer.h" 那么这两个模块包含相同的对象 comp

的定义
pragma once
class computer
{
public:
    computer();
    ~computer();
    void Select(void);
} comp;

因此链接器发出错误。

仅在一个 cpp 模块中定义对象。 header 应仅包含类定义。

例如

计算机.h

#pragma once
class computer
{
public:
    computer();
    ~computer();
    void Select(void);
};

井字游戏.cpp

// TicTacToe.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include "computer.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    computer comp;

    comp.Select();
    Sleep(1000);
}

关于c++ - 错误 : Class computer comp is already defined in computer. 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23979783/

相关文章:

c++ - wxRichTextCtrl 不工作?

c++ - 包括不工作的 guard ? (500 个类型为 LNK2005 x 的错误已在 y.obj 中定义)

c++ - 命名空间和包含生成链接错误

c++ - 包括 Boost 文件系统头文件

c++ - VS2019 C++成员函数LNK2005错误

c++ - 我可以使用 Qt LGPL 许可证并在没有任何限制的情况下出售我的应用程序吗?

c++ - ostringstream operator[] 在尝试读取缓冲区时给出编译错误

c++ - 唯一指针和 3 法则

c++ - 构建 cpp-netlib 共享库

添加新头文件时出现 C++ 错误 LNK2005