c++ - 使用未声明的标识符 C++

标签 c++ class oop allegro5

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

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

我在下面包含了源代码:

ma​​in.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/

相关文章:

使用 unique_ptr 的 C++ char 数组

c++ - 异步网络调用

class - 工厂设计模式和管道设计模式有什么区别?

oop - 我应该使这些方法成为非静态的吗

c# - C# 中的 getter 和 setter 有什么用?我如何将它们与数组一起使用?

c++ - 用于 openmp 4.5 卸载到 (gpu) 设备的 nvptx gcc (9.0.0/trunk) 找不到 libgomp.spec

c++ - 如何处理非客户区的按钮事件

C++ 通用对象指针

Python 将元素添加到一个实例的列表中也会将其添加到另一个实例的列表中

function - 如何重载 TypeScript 中的方法?