gpt4 book ai didi

c++ - 在 C++ 中创建对象时出现 "Unresolved External Symbol"错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:07 25 4
gpt4 key购买 nike

我是一个经验丰富的程序员,但我现在才刚刚开始研究 C++,它……好吧……比 PHP 和 Python 更难。尝试从某些类创建对象时,我一直遇到 Unresolved external 错误。它被分解成多个标题和文件,但这是我的一个类(class)的基本思想:

die.h:

#ifndef DIE_H
#define DIE_H

using namespace std;

class Die {
public:
int throwDie();
Die();
};

#endif

die.cpp

#include <iostream>
#include <cstdlib>
#include "Die.h"

using namespace std;

int Die::throwDie()
{
return 0;
}

sixsidedie.h

#ifndef SIXSIDEDIE_H
#define SIXSIDEDIE_H

#include "Die.h"

using namespace std;

class SixSideDie : public Die
{
public:
SixSideDie();
int throwDie();

private:
int randNumber;
};

#endif

sixsidedie.cpp

#include <iostream>
#include <cstdlib>
#include <time.h>
#include "Die.h"
#include "SixSideDie.h"

using namespace std;

const int SIX_SIDE = 6;

int SixSideDie::throwDie()
{
srand((unsigned int)time(0));
SixSideDie::randNumber = rand() % SIX_SIDE + 1;
return SixSideDie::randNumber;
}

main.cpp

#include <iostream>
#include <cstdlib>
#include "Die.h"
#include "SixSideDie.h"
#include "TenSideDie.h"
#include "TwentySideDie.h"

using namespace std;

int main()
{
Die* myDice[3];
myDice[0] = new SixSideDie();
myDice[1] = new TenSideDie();
myDice[2] = new TwentySideDie();

myDice[0]->throwDie();
myDice[1]->throwDie();
myDice[2]->throwDie();

system("pause");
return 0;
}

它一直告诉我,我直接在上面创建的每个对象都是一个未解析的外部符号,我只是不知道为什么。有什么想法!?

最佳答案

您为 Die 声明了一个构造函数,但从未定义它。

此外,如果您打算在派生类中覆盖它的行为,您几乎肯定希望 throwDie 是虚拟的,并且您永远不应该在 header 中使用 using namespace std;文件(很多人,包括我在内,会争辩说你根本不应该在文件范围内使用它)。

关于c++ - 在 C++ 中创建对象时出现 "Unresolved External Symbol"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3774931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com