我有一个带有虚拟方法的类定义。
在编译时,我收到错误消息:'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/