8

我不知道为什么这段代码不起作用。所有源文件都会编译,但是当我尝试链接它们时,编译器会以未定义的引用错误对我大喊大叫。这是代码:

主.cpp:

#include "SDL/SDL.h"
#include "Initilize.cpp"

int main(int argc, char* args[]) 
{
    //Keeps the program looping
    bool quit = false;
    SDL_Event exit;
    //Initilizes, checks for errors
    if(Initilize::Start() == -1) 
    {
        SDL_Quit();
    }
    //main program loop
    while(quit == false) 
    {
        //checks for events
        while(SDL_PollEvent(&exit)) 
        {
            //checks for type of event;
            switch(exit.type) 
            {
                case SDL_QUIT:
                quit = true;
                break;
            }
        }
    }
    return 0;
}

初始化.h:

#ifndef INITILIZE_H
#define INITILIZE_H
#include "SDL/SDL.h"

/* Declares surface screen, its attributes, and Start(); */
class Initilize {
protected:
    static SDL_Surface* screen;
private:
    static int SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP;
public:
    static int Start();
};

#endif

初始化.cpp:

#include "Initilize.h"
#include "SDL/SDL.h"

/* Initilizes SDL subsystems, sets the screen, and checks for errors */
int Initilize::Start() 
{
    //screen attributes
    SCREEN_WIDTH = 640;
    SCREEN_HEIGHT = 480;
    //Bits per pixel
    SCREEN_BPP = 32;
    //Inits all subsystems, if there's an error, return 1   
    if(SDL_Init(SDL_INIT_EVERYTHING) == -1) {
            return 1;
    }
    //sets screen
    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
    //Returns 1 if there was in error with setting the screen
    if(screen == NULL) {
            return 1;
    }
    SDL_WM_SetCaption("Game", NULL);
    return 0;
}

抱歉,如果代码的格式很奇怪,在代码块中插入四个空格会使事情变得有点混乱。

4

3 回答 3

16

将以下内容添加到您的 cpp 文件中:

SDL_Surface* Initilize::screen = 0; // or nullptr
int Initilize::SCREEN_WIDTH = 640;
int Initilize::SCREEN_HEIGHT = 480;
int Initilize::SCREEN_BPP = 32;

此外,如果这些值永远不会改变,那么制作它们会很好const。您需要将以上内容添加到您的 cpp 文件的原因是因为静态成员变量需要在类之外定义。static SDL_Surface* screen;等在你的类中只是一个声明,而不是一个定义。static成员被认为是特殊的,并且与全局变量非常相似。

这是因为静态成员在类的所有实例之间共享。这意味着它们只能定义一次,并且允许在类内定义会导致出现多个定义,因此 C++ 标准强制您在类外定义它(并且还暗示您应该将定义放在 cpp 文件中)。

于 2012-08-24T23:41:09.033 回答
2

Initialize.cpp

#include "Initialize.h"
#include "SDL/SDL.h"

// this is the new line to insert
SDL_Surface* Initialize::screen = 0;
int Initialize::SCREEN_WIDTH=...; // whatever you want to set it to
int Initialize::SCREEN_HEIGHT=...; // whatever you want to set it to
int Initialize::SCREEN_BPP=...; // whatever you want to set it to

并删除#include "Initialize.cpp"main.cpp 中的行

而是做

#include "Initialize.hpp"

如果你使用 gcc,编译使用

g++ -o <output-file> main.cpp Initialize.cpp <include flags like -I> <lib flags like -L>
于 2012-08-24T23:44:20.467 回答
1

看来您从未初始化过变量。您在 Initialize start 方法中分配它们,但没有初始化它们。在源文件中分配它之前尝试添加,int SCREENWIDTH;而不仅仅是头文件

于 2012-08-24T23:29:05.500 回答