【问题标题】:How to call static method from another class?如何从另一个类调用静态方法?
【发布时间】:2013-10-18 11:44:58
【问题描述】:

我正在尝试将 静态方法 从 a.h 调用到 b.cpp。根据我的研究,它就像放置 :: 范围解析一样简单,但是我尝试过,它给我一个错误“C++ 需要所有声明的类型说明符”。以下是我所拥有的。

a.cpp

float method() {
   //some calculations inside
}

啊.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.

我很困惑,需要指导。

【问题讨论】:

  • hmm,method 在我看来不像是一个实际的方法,只是一个普通的函数。
  • 删除a::。只需method();,它更干净。
  • 您是否显示了所有的相关代码?静态方法class的一部分。如果method 不在一个类中,您不希望static 用于该声明。
  • in a.h put static float a::method();
  • 您的最后一行 a method(); 不会抛出任何错误,因为这被解释为函数声明。

标签: c++ visual-c++ c++11 c++-cli c++builder


【解决方案1】:

如果你只是有

#include "b.h"
method();

你只是在“无处”中间转储一些指令(在某个地方你可以声明一个函数,定义一个函数或做一些邪恶的事情,比如定义一个全局,所有这些都需要一个类型说明符开始)

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

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

编辑

如果你在一个类中确实有一个静态方法,比如class A 在名为a.h 的标头中声明,你可以这样调用它,使用你所说的范围解析运算符,注意不要转储随机函数调用在全局范围内,但将它们放在方法中。

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

如果问题也是如何声明和定义静态方法,这就是这样做的方法: 在 a.h 中:

#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;
}

【讨论】:

  • 没关系,我已经让它工作了。谢谢你的帮助。原来是我的 shift 键有问题,我最终打字;我没有意识到对不起:/
  • 很高兴它已排序。换个新键盘 :-)
【解决方案2】:

很难理解你想要做什么。尝试类似:

啊.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')
}

【讨论】:

  • 嘿,我已经开始工作了。感谢你的帮助。原来是我的 shift 键有问题,我最终打字;我没有意识到对不起:/
猜你喜欢
  • 1970-01-01
  • 2015-02-13
  • 2010-12-24
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多