帮助C ++静态方法 [英] Help with C++ static method
问题描述
有可能从C ++中的静态方法返回对象,就像在Java中一样吗?我这样做:
Is it possible to return an object from a static method in C++ like there is in Java? I am doing this:
class MyMath {
public:
static MyObject calcSomething(void);
private:
};
我想这样做:
And I want to do this:
int main() {
MyObject o = MyMath.calcSomething(); // error happens here
}
在MyMath类中只有静态方法,没有点实例化它。但我得到这个编译错误:
There are only static methods in the MyMath class, so there's no point in instantiating it. But I get this compile error:
MyMath.cpp:69:错误:预期的主表达式'。'token
MyMath.cpp:69: error: expected primary-expression before '.' token
我做错了什么?我是否已实例化MyMath?
What am I doing wrong? Do I have to instantiate MyMath? I would rather not, if it is possible.
推荐答案
使用 ::
c>
Use ::
instead of .
MyObject o = MyMath :: calcSomething code>
MyObject o = MyMath::calcSomething();
当你调用没有类的对象的方法时,你应该使用 ::
符号。你也可以通过类对象或指向它们的指针调用静态方法,在这种情况下你应该使用通常的。
或 - >
符号:
When you are calling the method without the object of the class you should use ::
notation. You may also call static method via class objects or pointers to them, in this case you should use usual .
or ->
notation:
MyObject obj;
MyObject* p = new MyObject();
MyObject::calcSomething();
obj.calcSomething();
p->calcSomething();
这篇关于帮助C ++静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!