我最近一直在學習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;
}
呵呵,沒發現這一點。謝謝!順便說一句,是否將星號與返回類型放在一起,因爲這會提高可讀性?即「ALLEGRO_BITMAP *」而不是「ALLEGRO_BITMAP *」? – Calculus5000
這真的只是一種風格的東西。當它是一個函數的返回值時,我傾向於將星號放在左側,而當它是變量聲明或取消引用時,則放在右側。 – Olipro