简体   繁体   中英

“Unresolved External Symbol” errors when creating object in C++

I'm a pretty seasoned programmer but I'm just now diving into C++ and it's... well... more difficult than PHP and Python. I keep having unresolved external errors when trying to create an object from some classes. It's broken up into multiple headers and files but here is a basic idea from one of my classes:

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

It keeps telling me that each object I create directly above is an unresolved external symbol and I just don't know why. Any thoughts!?

You declared a constructor for Die but never defined it.

Also, you almost certainly want throwDie to be virtual if you intend to override its behavior in derived classes, and you should never use using namespace std; in a header file (and many people, including me, would argue that you shouldn't use it at file-scope at all).

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

Its good practice to define the constructors of the classes. Check this out:

#ifndef DIE_H
#define DIE_H

using namespace std;

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

#endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM