2015-09-21 126 views
0

我最近一直在學習C++,並且一直試圖創建一個簡單的類,將其拆分爲一個頭文件&源文件。但是,我似乎不斷收到此錯誤:使用未聲明的標識符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; 
} 

回答

4

您沒有正確定義的功能。 get_image()Ship類的成員。您的定義創建了一個獨立的功能。

ALLEGRO_BITMAP *get_image(){ 

應該是:

ALLEGRO_BITMAP* Ship::get_image(){ 

(星號重新定位爲可讀性)

+0

呵呵,沒發現這一點。謝謝!順便說一句,是否將星號與返回類型放在一起,因爲這會提高可讀性?即「ALLEGRO_BITMAP *」而不是「ALLEGRO_BITMAP *」? – Calculus5000

+1

這真的只是一種風格的東西。當它是一個函數的返回值時,我傾向於將星號放在左側,而當它是變量聲明或取消引用時,則放在右側。 – Olipro

1

,因爲它是目前定義,get_image()僅僅是一個擁有無關,與你的類的功能。它位於ship.cpp這一事實是無足輕重的。既然你想實現的Ship類的方法,你需要定義與Ship::前綴的實現:

ALLEGRO_BITMAP* Ship::get_image() { 
    return image; 
}