Program Has Unexpectedly Finished
My execution program won't work properly, for whatever reason.
#include <QtCore/QCoreApplication>
#include <tinyxml/tinyxml.h>
#include "classowner.h"
#include "character.h"
int main(int argc, char *argv[])
{
Character * holland = new Character("Holland", HUMAN, MALE);
delete &holland;
std::cout << "Hello, World!" << std::endl;
return 0;
}
All my output states is that the program won't execute properly. The output doesn't display, however when I don't allocate the object, it will. Obviously, it's the object. What am I doing wrong?
Update
It appears the problem may be something more than deleting and allocating memory. Thus, I'm going to post the implementation behind the Character class.
Header:
#include <iostream>
#ifndef CHARACTER_H
#define CHARACTER_H
enum Race {HUMAN, DARK_ELF};
enum Gender {MALE, FEMALE};
class Character
{
public:
Character();
Character(std::string char_name, Race char_race, Gender char_gender);
~Character();
int get_id() { return this->char_id; }
std::string get_name() { return this->name; }
Race get_race() { return this->race; }
Gender get_gender() { return this->gender; }
private:
int char_id;
static int * char_count;
std::string name;
Race race;
Gender gender;
};
#endif // CHARACTER_H
//Source:
#include "character.h"
#include <iostream>
int * Charact开发者_Go百科er::char_count = 0;
Character::Character()
{
this->char_id = *char_count;
char_count++;
}
Character::Character(std::string char_name, Race char_race, Gender char_gender)
{
this->char_id = *char_count;
char_count++;
this->name = char_name;
this->race = char_race;
this->gender = char_gender;
}
Character::~Character()
{
}
delete &holland;
should be
delete holland;
Less profanity would be appreciated.
On the other hand, posting a short example that succinctly illustrates the problem is very much appreciated.
First of all, you try to dereference a null pointer:
int * Character::char_count = 0;
Both constructors of class Character
do this
this->char_id = *char_count;
and that's an attempt to dereference a null pointer. That code makes no sense to me, I guess you could just use int
instead of pointer:
int Character::char_count = 0;
//then
this->char_id = char_count;
Also here:
Character * holland = new Character("Holland", HUMAN, MALE);
you create an object of type class Character
. You have to delete that object through a pointer to class Character
- the pointer should have type Character*
. Instead you try to use delete
on a pointer of type Character**
and that leads to undefined behavior.
So instead of
delete &holland;
you have to use
delete holland;
精彩评论