【问题标题】:Use of undeclared identifier C++使用未声明的标识符 C++
【发布时间】:2015-09-21 21:23:30
【问题描述】:

我最近一直在学习 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;
}

【问题讨论】:

    标签: c++ class oop allegro5


    【解决方案1】:

    您错误地定义了函数。 get_image()Ship 类的成员。您的定义创建了一个独立的函数。

    ALLEGRO_BITMAP *get_image(){
    

    应该是:

    ALLEGRO_BITMAP* Ship::get_image(){
    

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

    【讨论】:

    • 哦,没发现。谢谢!顺便说一句,将星号与返回类型放在一起是否可以提高可读性?即 ALLEGRO_BITMAP* 而不是 ALLEGRO_BITMAP *?
    • 这真的只是一个风格的东西。当它是函数的返回值时,我更喜欢将星号放在左侧,而当它是变量声明或取消引用时,我更喜欢将星号放在右侧。
    【解决方案2】:

    按照目前的定义,get_image() 只是一个与您的类无关的函数。它位于ship.cpp 的事实无关紧要。由于您正在尝试实现Ship 类的方法,因此您需要使用Ship:: 前缀定义实现:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多