c++ - 编译错误 - 静态成员

标签 c++ static-methods

我有一个带有虚拟方法的类定义。

在编译时,我收到错误消息:'MethodType Class::Method' is not a static member of class Class

我找到的最流行的解决方案是在头文件中的方法定义中添加关键字static

但是,该方法被定义为虚拟。因此,要添加 static 关键字,我必须删除 virtual 关键字。不幸的是,这无法完成,因为该类继承自父级,其中此方法也被声明为 virtual,从而导致另一个编译器错误。 (请注意,我使用的是定义的接口(interface),无法访问父类的源代码)

有没有人有什么想法?


头文件:

class X : public OtherClass
{
   public:
      X();
      ~X();  

     virtual structType MethodName(ParamType1,ParamType2);

};

然后在我的 CPP 文件中:

structType * X::MethodName(ParamType1 P1, ParamType2 P2)
{
   //Implementation here
}

这会被标记为错误:

'structType* X::MethodName' is not a static member of 'class X'

最佳答案

如果您想在没有该类的对象的情况下调用方法,则必须将其设置为static。这对虚拟方法没有意义。
您必须创建该类的一个对象,然后调用该方法。

struct X {
   static int bar();
   int foo();

};

X::bar(); // Works, static method called
X::foo(); // Doesn't work (your problem)

X x;
x.bar(); // Works, but X::bar() recommended (so that one sees that it's static...)
x.foo(); // Works, your solution

关于c++ - 编译错误 - 静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6149995/

相关文章:

php - 使用 MySQLi 的 real_escape_string 作为静态函数

c++ - 如何为模板类的 const ref 成员定义 move 赋值运算符

c++ - 无法从 'const char [3]' 转换为 'char *' x100000 (Qt Creator C++ Windows 32)

C++循环数据结构

c++ - 在对象实例上调用静态函数时解析错误?

java - 如何从静态上下文引用非静态方法 'findViewById'?

c++ - Windows 上 C++ 中非常不同的 I/O 性能

c++ - 奇怪的 GDAL 编译错误

PhpStorm PHPDocs 文档静态外观类类型以启用自动完成

c++ - 重写 C++ 中的静态方法