[英]How to call static method from another class?
我试图从ah到b.cpp调用一个静态方法 。 从我研究的内容来看,它就像放置一个:: scope解决方案一样简单,但是我尝试了它并且它抛出了一个错误“C ++需要所有声明的类型说明符”。 以下就是我所拥有的。
a.cpp
float method() {
//some calculations inside
}
啊
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.
我很困惑,需要指导。
如果你只是
#include "b.h"
method();
你只是在“无处”中间抛出一些指令(在某处你可以声明一个函数,定义一个函数或做一些邪恶的事情,比如定义一个全局,所有这些都需要一个类型说明符开始)
如果你从另一个方法调用你的函数,比如说main
编译器会认为你正在调用一个方法,而不是试图声明一些东西并且没有说出它是什么类型。
#include "b.h"
int main()
{
method();
}
编辑
如果你在一个类中确实有一个静态methid,比如在一个名为ah
的头文件中声明的class A
你用这种方式调用它,正如你所说的那样使用scope resoution运算符,注意不要在全局范围内转储随机函数调用,而是把它们放在内部方法中。
#include "a.h"
int main()
{
A::method();
}
如果问题也是如何声明和定义静态方法,这就是这样做的方法:在啊:
#ifndef A_INCLUDED
#define A_INCLUDED
class A{
public :
static float method();
};
#endif
然后在a.cpp中定义它
#include "a.h"
float A::method()
{
//... whatever is required
return 0;
}
很难理解你正在尝试做什么。 尝试类似的东西:
啊
// 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')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.