当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Function not found in scope of main

问题描述:

I have a problem, normally I would understand why this is happening, I didnt declare the function in the main method. But the class itself includes the .h file, which has the prototype for this method, so I am a bit lost on why it is not in the scope of the main function.

 using namespace std;

#include "Solar.h"

int main(){

initializeGL();

Stars *Alpha = new Stars(5.0);

Planets *Awe = new Planets(.6,2,30,"Awe",0.0,0.0,0.0);

paintGL();

return 0;

}

void Solar::initializeGL(){

glShadeModel(GL_SMOOTH);

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glClearDepth(1.0f);

glEnable(GL_DEPTH_TEST);

glDepthFunc(GL_LEQUAL);

glHint(GL_PERSPECTIV

....

}

There is also a function paintGL() later on, and here is the header file

 class Solar {

public:

void initializeGL();

void resizeGL(int width, int height);

void paintGL();

.....

private:

.....

};

I am not the best with c++, so anyhelp will be appreciated.

ANd here is the error

Solar.cpp:4: error: declaration of âvoid Solar::initializeGL()â outside of class is not definition

Solar.cpp:5: error: declaration of âvoid Solar::paintGL()â outside of class is not definition

Solar.cpp: In function âint main()â:

Solar.cpp:8: error: âinitializeGLâ was not declared in this scope

Solar.cpp:11: error: âpaintGLâ was not declared in this scope

网友答案:

Solar is a class, and initializeGL and paintGL are member functions. If you wanted to use them, you would have to create an instance of Solar.

Solar solar;
solar.initializeGL();
// ...more
solar.paintGL();

Read up on member functions: http://msdn.microsoft.com/en-us/library/fk812w4w.aspx

网友答案:

The paintGL() function is a member function of the class Solar. You can only call it on an object of type Solar:

Solar s;
s.paintGL();

If you want to be able to call it without object, you should either make it a free function, or a static member function:

// free
void paintGL();

// static member
class Solar {
public: static void paintGL();
};

This of course only works if paintGL uses no member data of Solar...

网友答案:

Both functions are instance functions; you need to instantiate a new Solar object and call the functions from it, not out of scope like you did

网友答案:

initializeGL and paintGL are both member functions of the Solar class, but you're trying to call them like they are global functions. That won't work.

You either need an instance of Solar:

int main(){
  Solar* solar = ... // magic

  solar->initializeGL();
  Stars *Alpha = new Stars(5.0);
  Planets *Awe = new Planets(.6,2,30,"Awe",0.0,0.0,0.0);
  solar->paintGL();

...or make the functions static member functions:

class Solar {
 public:
  static void initializeGL();
  void resizeGL(int width, int height);
  static void paintGL();
  .....
private:
  .....
};

...or (worst option by far), make them global functions.

分享给朋友:
您可能感兴趣的文章:
随机阅读: