如何调用C ++静态方法 [英] How to call C++ static method

查看:129
本文介绍了如何调用C ++静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像Java中那样从C ++中的静态方法返回对象?我正在这样做:

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

我想这样做:

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:错误:预期的主表达式位于'。'标记之前

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.

推荐答案

使用 :: 而不是

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆