我最近一直在学习C ++,并且一直在尝试创建一个分为头文件和源文件的简单类。但是,我似乎继续收到此错误:

ship.cpp:21:9: error: use of undeclared identifier 'image'
        return image;
               ^
1 error generated.


我已包含以下源代码:

main.cpp:

#include <iostream>

#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_native_dialog.h>

#include <ship.h>

int main(int argc, char **argv){
    ALLEGRO_DISPLAY *display = nullptr;
    ALLEGRO_BITMAP *image = nullptr;


    if(!al_init()){
        al_show_native_message_box(display, "Error", "Error", "Failed to initialise allegro", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return 0;
    }

    if(!al_init_image_addon()) {
        al_show_native_message_box(display, "Error", "Error", "Failed to initialize al_init_image_addon!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return 0;
    }

    display = al_create_display(800,600);
      if(!display) {
        al_show_native_message_box(display, "Error", "Error", "Failed to initialize display!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return 0;
      }


    Ship ship("image.jpg");
    al_draw_bitmap(ship.get_image(), 200, 200, 0);

    al_flip_display();
    al_rest(2);
    return 0;
}


ship.h:

#ifndef SHIP_H
#define SHIP_H
#include <iostream>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>

class Ship
{
    ALLEGRO_BITMAP *image;

    private:
        int width;
        int height;

    public:
        Ship(std::string image_file);
        ALLEGRO_BITMAP *get_image();
};

#endif


ship.cpp:

#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_native_dialog.h>
#include <iostream>

#include <ship.h>




Ship::Ship(std::string image_file){
    image = al_load_bitmap(image_file.c_str());
    if(image == nullptr){
        std::cout << "Ship went down." << std::endl;
    }
    std::cout << "Ship loaded successfully." << std::endl;
}


ALLEGRO_BITMAP *get_image(){
    return image;
}

最佳答案

您未正确定义函数。 get_image()Ship类的成员。您的定义将创建一个独立的函数。

ALLEGRO_BITMAP *get_image(){


应该:

ALLEGRO_BITMAP* Ship::get_image(){


(为便于阅读,将星号重新定位)

关于c++ - 使用未声明的标识符C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32704783/

10-11 02:54