How to call static method from another class?

2019-06-25 12:01发布

I am trying to call a static method from a.h to b.cpp. from what I have researched, it is as simple as just putting a :: scope resolution but however I tried and it throws me an error "C++ requires a type specifier for all declarations". below is what I have.

a.cpp

float method() {
   //some calculations inside
}

a.h

static float method();

b.cpp

 a::method(); <- error!  "C++ requires a type specifier  for all declarations".
 but if I type without the ::
 a method(); <- doesn't throw any errors.

I quite confused and need guidance.

2条回答
Anthone
2楼-- · 2019-06-25 12:15

It's tough to understand what it is you're trying to do. Try something like:

a.h

// header file, contains definition of class a
// and definition of function SomeFunction()

struct a {
    float method();
    static float othermethod();
    static float yetAnotherStaticMethod() { return 0.f; }

    float value;
}

float SomeFunction();

a.cpp

// implementation file contains actual implementation of class/struct a
// and function SomeFunction()

float a::method() {
   //some calculations inside
   // can work on 'value'
   value = 42.0f;
   return value;
}

float a::othermethod() {
    // cannot work on 'value', because it's a static method
    return 3.0f;
}

float SomeFunction() {
     // do something possibly unrelated to struct/class a
     return 4.0f;
}

b.cpp

#include "a.h"
int main()
{
     a::othermethod();  // calls a static method on the class/struct  a
     a::yetAnotherStaticMethod();  // calls the other static method

     a instanceOfA;

     instanceOfA.method();   // calls method() on instance of class/struct a (an 'object')
}
查看更多
beautiful°
3楼-- · 2019-06-25 12:29

If you simply have

#include "b.h"
method();

you are just dumping some instructions in the middle of "nowhere" (well somewhere you could declare a function, define a function or do something evil like define a global, all of which require a type specifier to start with)

If you call your function from another method, say main the compiler will think you are calling a method rather than trying to declare something and failing to say what type it is.

#include "b.h"
int main()
{
    method();
}

edit

If you really have a static methid in a class, say class A declared in a header called a.h you call it this way, using the scope resoution operator as you have said, being careful not to dump random function calls at global scope, but to put them inaside methods.

#include "a.h"
int main()
{
    A::method();
}

If the question is also how to declare and define the static method this is the way to do it: in a.h:

#ifndef A_INCLUDED
#define A_INCLUDED

class A{

public :       
      static float method(); 

}; 
#endif

and then define it in a.cpp

#include "a.h"

float A::method()
{
    //... whatever is required
    return 0;
}
查看更多
登录 后发表回答