C++ - “函数的多重定义”我们如何解决它?
Posted
技术标签:
【中文标题】C++ - “函数的多重定义”我们如何解决它?【英文标题】:C++ - "Multiple Definition of functions" How do we fix it? 【发布时间】:2020-11-06 05:04:50 【问题描述】:我是 C++ 编程的新手。我对 c++ 中的 oop 没有任何想法。但我只知道循环、if else 结构和 switch-case 语句等基础知识。我决定用 C++ 编写井字游戏。没有面向对象编程,它太大了。但我还是决定这样做。在修复了一堆错误之后,我收到了这个错误:“同一函数的多个定义”,我不知道如何解决这个问题。我一共使用了四个文件(在 code::blocks 中)。 主文件:
//main.cpp
//Tic-Tac-Toe game
#include <iostream>
#include "Untitled1.cpp"
#include "Untitled2.cpp"
#include "Untitled3.cpp"
using namespace std;
int main()
cout << "HII\nWelcome to Tic-Tac-Toe!!!\nEnter 1 to play with yourself\nEnter 2 to play with someone who's with you\nEnter 3 to play with the computer ";
string num;
krrish:
cin >> num;
// <EXCEPTION HANDLING>
while ((num != "1") && (num != "2") && (num != "3"))
cout << "I guess you didn't understand!!\n\nEnter 1 to play with yourself\nEnter 2 to play with someone who's with you\nEnter 3 to play with the computer ";
goto krrish;
// </EXCEPTION HANDLING>
if (num == "1")
playwithyourself();
else if (num == "2")
playwithanotherone();
else if (num == "3")
playwithcomputer();
return 0;
在这个文件中,我使用了其他三个包含上面声明的函数的文件。 无标题1.cpp:
#include <iostream>
using namespace std;
int playwithyourself()
/////4828 LINES OF CODE INSIDE; TOOK ME WEEKS TO WRITE THIS; ITS LONG COZ I DUNNO OOP
Untitled2.cpp
#include <iostream>
using namespace std;
int playwithanotherone()
//Left empty haha, not written yet
Untitled3.cpp
#include <iostream>
using namespace std;
int playwithcomputer()
//Left empty haha, not written yet
当我编译 main.cpp 时,它显示三个函数的此错误:“'(函数名称)'的多重定义” 它还显示此错误:“1d 返回 1 退出状态” 说真的,我搞砸了。
【问题讨论】:
确保在类和函数定义中使用guard。使用#ifndef、#define 和#endif。 这能回答你的问题吗? Multple c++ files causes "multiple definition" error? 这能回答你的问题吗? How to include a cpp file in two different cpp files that are linked? 看来你编译了所有四个 cpp 文件并将它们链接到一个可执行文件。你能告诉我你的构建命令是什么 【参考方案1】:第一个功能:
#ifndef TEST_PLAYWITHYOURSELF_H
#define TEST_PLAYWITHYOURSELF_H
#include <iostream>
using namespace std;
int playwithyourself()
/////4828 LINES OF CODE INSIDE; TOOK ME WEEKS TO WRITE THIS; ITS LONG COZ I DUNNO OOP
#endif //TEST_PLAYWITHYOURSELF_H
第二个功能:
#ifndef TEST_PLAYWITHANOTHERONE_H
#define TEST_PLAYWITHANOTHERONE_H
#include <iostream>
using namespace std;
int playwithanotherone()
//Left empty haha, not written yet
#endif //TEST_PLAYWITHANOTHERONE_H
第三个功能:
#ifndef TEST_PLAYWITHCOMPUTER_H
#define TEST_PLAYWITHCOMPUTER_H
#include <iostream>
using namespace std;
int playwithcomputer()
//Left empty haha, not written yet
#endif //TEST_PLAYWITHCOMPUTER_H
使用上面的代码,就可以正常工作了!
【讨论】:
请把错误放在这里。我已经使用 gcc 版本 9.3.0 编译了上面的代码。以上是关于C++ - “函数的多重定义”我们如何解决它?的主要内容,如果未能解决你的问题,请参考以下文章