静态函数访问类成员

时间:2013-05-29 14:07:32

标签: c++ class static-members static-functions

班级标题:

#ifndef _APP_H_
#define _APP_H_

#include "glut.h"
#include "Declare.h"


class App {
private:
    static float angle; 

public:

    App();
    int OnExecute();
    void OnLoop();
    static void OnRender();
    bool OnInit();
    void OnCleanup();
    static void OnResize(int w, int h);


};


#endif

我对OnRender的定义是

#include "App.h"

App::App() {
    angle = 0.0f;
}

void App::OnRender() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    gluLookAt( 0.0f, 0.0f, 10.0f,
               0.0f, 0.0f, 0.0f,
               0.0f, 1.0f, 0.0f);
    glRotatef(angle, 0.0f, 1.0f, 0.0f);

    glBegin(GL_TRIANGLES);
        glVertex3f(-2.0f,-2.0f,0.0f);
        glVertex3f(2.0f,0.0f,0.0f);
        glVertex3f(0.0f,2.0f,0.0f);
    glEnd();

    angle+=0.1f;

    glutSwapBuffers();
}

错误:

1>App.obj : error LNK2001: unresolved external symbol "private: static float App::angle" (?angle@App@@0MA)
1>App_OnRender.obj : error LNK2019: unresolved external symbol "private: static float App::angle" (?angle@App@@0MA) referenced in function "public: static void __cdecl App::OnRender(void)" (?OnRender@App@@SAXXZ)

与我如何在静态函数中引用静态变量有关。如果我没有将角度声明为static float angle,那么我当然无法通过static void OnRender()访问它。我必须添加更多细节。如果我没有将其声明为静态,我会收到此错误illegal reference to non-static member App::angle

1 个答案:

答案 0 :(得分:3)

在源文件App.cpp中,您需要 定义 您的静态变量:

static float App::angle = 0; //0 is my test default value. use yours

如果您想在非静态方法中使用angle可能希望将类实例与App:angle一起使用。例如:

App::App() {
    App::angle = 0.0f;
}