C ++变量未正确实例化

时间:2012-12-16 13:21:10

标签: c++

Sprite1 *test = new Sprite1(450, 450, "enemy.bmp", *screen);
    test->DrawJon();
    SDL_Delay(1000);
    test->MoveJon(20,20);

我在第2行遇到运行时错误。它表示访问冲突在0x0

Sprite1是我定义的类,类中的DrawJon()和MoneJon()。这种语法对编译器没用,但在运行时失败。

Sprite1.cpp

#include "Sprite1.h"

Sprite1::Sprite1(int posX, int posY, std::string imagePath, SDL_Surface screen) :     PosX(posX), PosY(posY), ImagePath(imagePath), Screen(screen)
{
void DrawSprite1Jon( int x, int y, SDL_Surface *sprite, SDL_Surface *screen );
void DrawJon();
void MoveJon(int xDist, int yDist);
}

void Sprite1::DrawSprite1Jon( int x, int y, SDL_Surface *sprite, SDL_Surface *screen )
{
//Make a temporary rectangle to hold the offsets
SDL_Rect offset;

//Give the offsets to the rectangle
offset.x = x;
offset.y = y;

//Blit the surface
SDL_BlitSurface( sprite, NULL, screen, &offset );

SDL_UpdateRect(screen, 0, 0, 0, 0);
}

void Sprite1::DrawJon()
{
#pragma region Char to String Conversion

string ImagePath;
char * writable = new char[ImagePath.size() + 1];
copy(ImagePath.begin(), ImagePath.end(), writable);
writable[ImagePath.size()] = '\0';

#pragma endregion

temp = SDL_LoadBMP(writable);
sprite = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);

// free the string after using it
delete[] writable;

DrawSprite1Jon(PosX, PosY, sprite, screen);
}

Sprite1.h

#include <string>
#include <SDL.h>
#include "Functions.h"

using namespace std;

class Sprite1
{
private:
    int PosX;
    int PosY;
    int xDist;
    int yDist;
    string ImagePath;
    SDL_Surface Screen;
    SDL_Surface *temp, *sprite, *screen;

public:
    Sprite1(int PosX, int PosY, string ImagePath, SDL_Surface Screen );
    void DrawSprite1Jon( int x, int y, SDL_Surface *sprite, SDL_Surface *screen);
    void DrawJon();
    void MoveJon(int xDist, int yDist);
};

编辑:

经过进一步调查,正是这条线

DrawSprite1Jon(PosX, PosY, sprite, screen);

在DrawJon()

中失败了

3 个答案:

答案 0 :(得分:1)

至少这部分代码已损坏:

string ImagePath;
char * writable = new char[ImagePath.size() + 1];
copy(ImagePath.begin(), ImagePath.end(), writable);
writable[ImagePath.size()] = '\0';

您正在创建本地ImagePath变量,而不是使用类成员变量。局部变量 shadow 成员变量。删除局部变量(上面代码段中的第一行)。

另外,你可能(我对SDL不是很熟悉)加载就像这样:

temp = SDL_LoadBMP(ImagePath.c_str());

然后,只是猜测,但图像加载可能会失败,并且该函数返回NULL指针。因此,检查返回值,然后检查错误(可以调用一些SDL错误函数,或者需要检查标准的errno全局变量。

进一步的建议:打开编译器警告(对于gcc:-W -Wall)并学会理解(将警告复制到谷歌是一个好的开始),然后修复警告。大多数时候它们都是真正的错误(因此警告!),即使它们不是,修复警告也会使你的代码变得更好。

答案 1 :(得分:0)

我很明显你刚刚开始使用C ++编程,也许你有一个javascript背景,因此你试图将函数声明放入构造函数中。这是一个错误的想法。 (#pragma通常有一些明确的含义,你也在这里滥用它们。see eg. #pragma GCC poison

我在这段代码中看到很多混淆。

我建议你先拿一个great quality beginner C++ book,然后再继续这段代码。在这一点上,我认为没有理由试图从这段代码中敲定一些合理的东西。

答案 2 :(得分:0)

我的实现存在一些问题,但最终我必须构建在发布模式而不是调试模式。

相关问题