c ++ LNK2001:未解决的外部符号问题

问题描述

| 问候。 我已经在寻找解决方案,但是我认为这个问题是个人代码特定的,因此我在这里发布。 我会直截了当。 我主要有两个对象。
Computer *computer = new Computer();
Player *player = new Player();
在计算机类的标题中,我具有以下内容
  private:

Strategy *strategy;
int winningPosition;
int twoInRow;
int counter;
int makeTwo;
然后在Computer.cpp中:
Computer::Computer(char token,bool hasTurn)
{
    m_token = token;
    m_hasTurn = hasTurn;
    strategy = new Strategy();
}

int Computer::getMove(const char (&board)[9])
{
    twoInRow = strategy->checkTwoInRow(board);
    counter = strategy->counter(board);
    makeTwo = strategy->makeTwo(board);

    if(twoInRow != 0)
    {
        return twoInRow - 1;
    } else if(counter != 0) {
        return counter - 1;
    } else if(makeTwo != 0) {
        return makeTwo - 1;
    } else {
        return 0;
    }
}
在这一点上,我认为出现了问题。 从策略类中调用方法都需要董事会知识,因此:
int checkTwoInRow(const char (&board)[9]);
int counter(const char (&board)[9]);
int makeTwo(const char (&board)[9]);
问题越来越严重,无法编译:
Error   1   error LNK2019: unresolved external symbol \"public: int __thiscall Strategy::makeTwo(char const (&)[9])\" (?makeTwo@Strategy@@QAEHAAY08$$CBD@Z) referenced in function \"public: int __thiscall Computer::getMove(char const (&)[9])\" (?getMove@Computer@@QAEHAAY08$$CBD@Z)    C:\\CPP\\TTT\\Computer.obj tictactoeCPP

Error   2   error LNK2019: unresolved external symbol \"public: int __thiscall Strategy::counter(char const (&)[9])\" (?counter@Strategy@@QAEHAAY08$$CBD@Z) referenced in function \"public: int __thiscall Computer::getMove(char const (&)[9])\" (?getMove@Computer@@QAEHAAY08$$CBD@Z)    C:\\CPP\\TTT\\Computer.obj tictactoeCPP

Error   3   error LNK2019: unresolved external symbol \"public: int __thiscall Strategy::checkTwoInRow(char const (&)[9])\" (?checkTwoInRow@Strategy@@QAEHAAY08$$CBD@Z) referenced in function \"public: int __thiscall Computer::getMove(char const (&)[9])\" (?getMove@Computer@@QAEHAAY08$$CBD@Z)    C:\\CPP\\TTT\\Computer.obj tictactoeCPP
作为c ++新手,我完全不知道为什么或如何导致此问题。我认为它与计算机类中Strategy的实例化或方法调用中从计算机给Strategy的参数有关。 谁能解释为什么会发生此错误,我根本不太理解该错误。 以及如何解决/防止这种情况? 编辑* 我刚刚收到一个分享“策略”课程的请求: Strategy.h:
    #pragma once
class Strategy
{
public:
    Strategy(void);
    ~Strategy(void);

    int checkTwoInRow(const char (&board)[9]);
    int counter(const char (&board)[9]);
    int makeTwo(const char (&board)[9]);
};
类定义了这些方法,我不会发布它们,因为它们很长。     

解决方法

这是一个链接错误,与实例化或参数无关。 您尚未为链接器提供这些功能的定义。如果在Strategy.cpp中定义了它们,则需要对其进行编译,并将其作为参数添加到链接器。如何执行完全取决于您用来构建程序的工具。 如果您使用的是Visual Studio(或任何其他IDE),则应在将Strategy.cpp添加到项目后自动对其进行处理。 还是您可能这样定义它们:
int checkTwoInRow(const char (&board)[9])
{
   // Do something with board the wrong way
}
而不是像这样:
int Strategy::checkTwoInRow(const char (&board)[9])
{
   // Do something with board the right way
}
第一个没有定义Strategy成员函数,而是定义了一个全局函数。     ,错误只是说明您已声明但未定义成员函数
Strategy::makeTwo
Strategy::counter
Strategy::checkTwoInRow
。您确定已实现它们(在实际正在编译的源文件中)并且没有意外将它们定义为自由函数吗?