我最近一直在学习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;
}
答案 0 :(得分:4)
您已正确定义了该功能。 get_image()
是Ship
类的成员。您的定义创建了一个独立的功能。
ALLEGRO_BITMAP *get_image(){
应该是:
ALLEGRO_BITMAP* Ship::get_image(){
(为了便于阅读,重新定位了星号)
答案 1 :(得分:1)
正如它目前所定义的那样,get_image()
只是一个与你的班级无关的功能。它位于ship.cpp
的事实无关紧要。由于您尝试实现Ship
类的方法,因此需要使用Ship::
前缀定义实现:
ALLEGRO_BITMAP* Ship::get_image() {
return image;
}