如何从另一个类调用静态方法? [英] How to call static method from another class?

查看:315
本文介绍了如何从另一个类调用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从a.h到b.cpp调用静态方法。从我研究的,它是简单的只是把一个::范围的解决方案,但是我试过,它抛出一个错误C ++需要一个类型说明符的所有声明。下面是我有的。

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
}

ah

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.

推荐答案

如果你只有

#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)

如果你从另一个方法调用你的函数, code> main 编译器会认为你正在调用一个方法,而不是试图声明一个东西,而没有说出什么类型。

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();
}






/ strong>


edit

如果你真的有一个类中有一个静态的methid,说 class A ah 你这样调用,使用scope resoution操作符,如你所说,小心不要转储在全局范围的随机函数调用,而是把它们放在方法中。 / p>

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();
}

如果问题也是如何声明和定义静态方法,方法做:
in ah:

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

,然后在a.cpp中定义

and then define it in a.cpp

#include "a.h"

float A::method()
{
    //... whatever is required
    return 0;
}

这篇关于如何从另一个类调用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆