我有两个类,这是其中一个的标题:
#ifndef WRAPPER_HPP
#define WRAPPER_HPP
#include <SDL/SDL.h>
using namespace std;
class Wrapper
{
private:
//SDL_Surface *screen;
public:
static SDL_Surface *screen;
static void set_screen(SDL_Surface *_screen);
static void set_pixel(int x, int y, Uint8 color);
static void clear_screen(int r, int g, int b);
static SDL_Surface* load_image(char path[500]);
static void draw_image(SDL_Surface *img, int x, int y, int width, int height);
static void draw_line(int x1, int y1, int x2, int y2, Uint8 color);
};
#endif
Run Code Online (Sandbox Code Playgroud)
我从另一个文件调用Wrapper :: set_screen(屏幕),我收到此错误:
In file included from /home/david/src/aships/src/Wrapper.cpp:6:0:
/home/david/src/aships/src/Wrapper.hpp: In static member function ‘static void Wrapper::set_screen(SDL_Surface*)’:
/home/david/src/aships/src/Wrapper.hpp:11:18: error: invalid use of member ‘Wrapper::screen’ in static member function
/home/david/src/aships/src/Wrapper.cpp:10:3: error: from this location
Run Code Online (Sandbox Code Playgroud)
我也在Wrapper.cpp上定义每个函数时遇到类似的错误,例如:
void Wrapper::set_pixel(int x, int y, Uint8 color)
{
/* Draws a pixel on the screen at (x, y) with color 'color' */
Uint8 *p;
p = (Uint8 *) screen->pixels + y * screen->pitch + x * screen->format->BytesPerPixel;
*p = color;
}
Run Code Online (Sandbox Code Playgroud)
在编译时:
/home/david/src/aships/src/Wrapper.hpp: In static member function ‘static void Wrapper::set_pixel(int, int, Uint8)’:
/home/david/src/aships/src/Wrapper.hpp:11:18: error: invalid use of member ‘Wrapper::screen’ in static member function
/home/david/src/aships/src/Wrapper.cpp:17:17: error: from this location
Run Code Online (Sandbox Code Playgroud)
我知道这与静态类相关,因此变量Wrapper.screen不可访问或者其他东西,但我不确定如何修复它.有任何想法吗?
小智 5
您正在使用静态变量
static SDL_Surface *screen;
Run Code Online (Sandbox Code Playgroud)
在你的代码中.
在C++中,当您在.h(或.hpp)中声明一个静态变量时,您正在创建一个对该类通用(静态)的变量.因此,要在另一个文件中使用它,你必须重新声明它(我猜你没有)在该文件中创建一个引用静态变量的变量.在你的情况下把这个:
SDL_Surface* Wrapper::screen;
Run Code Online (Sandbox Code Playgroud)
在.cpp文件中.
我不确定这个理论是否得到了很好的解释,但它的确如此.