C ++-“函数的多个定义”我们如何解决?

问题描述

我是C ++编程的新手。我对C ++中的oop没有任何想法。但是我只知道诸如循环之类的基础知识,否则就了解结构和switch-case语句。我决定用C ++编写井字游戏。如果没有面向对象的编程,它太大了。但是我仍然决定这样做。修复了一堆错误之后,我得到了以下错误:“同一功能的多个定义”,我不知道如何解决此问题。我总共使用了四个文件(在代码:: 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;
}  

在此文件中,我使用了其他三个包含上述声明的功能文件。 Untitled1.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退出状态” 严重的是我搞砸了。

解决方法

第一个功能:

#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

使用上面的代码,它将正常工作!