我目前正在玩 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.cpp
和 TicTacToe.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/