在C ++中创建对象时出现“未解析的外部符号”错误

时间:2010-09-23 02:05:49

标签: c++ class inheritance

我是一位经验丰富的程序员,但我现在正在深入研究C ++,而且... ......比PHP和Python更难。尝试从某些类创建对象时,我一直有未解决的外部错误。它分为多个标题和文件,但这是我的一个类的基本想法:

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;
}

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

3 个答案:

答案 0 :(得分:5)

您为Die声明了一个构造函数,但从未对其进行过定义。

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

答案 1 :(得分:1)

您没有在cpp文件中定义构造函数。

答案 2 :(得分:1)

定义类的构造函数的好习惯。看看这个:

#ifndef DIE_H
#define DIE_H

using namespace std;

class Die {
 public: 
  int throwDie();
  Die() { };  // can you spot the difference here?
};

#endif
相关问题