How to call C++ static method

霸气de小男生 提交于 2019-11-29 11:16:51

问题


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
}

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: error: expected primary-expression before '.' token

What am I doing wrong? Do I have to instantiate MyMath? I would rather not, if it is possible.


回答1:


Use :: instead of .

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();



回答2:


What am I doing wrong?

You are simply using incorrect syntax... the :: operator (scope resolution operator) is how you would access classes or members in different namespaces:

int main() { 
    MyObject o = MyMath::calcSomething(); // correct syntax
}

Do I have to instantiate MyMath?

No.




回答3:


For this case, you want MyMath::calcSomething(). The '.' syntax is for calling functions in objects. The :: syntax is for calling functions in a class or a namespace.




回答4:


Call MyMath::calcSomething()




回答5:


Try this way

#include <iostream>
using namespace std;
class MyMath {  
public:
    static MyMath* calcSomething(void);
private:
};
MyMath* MyMath::calcSomething()
{
    MyMath *myMathObject=new MyMath;
    return myMathObject;
}
int main()
{   
    MyMath *myMathObject=MyMath::calcSomething();
    /////Object created and returned from static function calcSomeThing   
}

Thanks



来源:https://stackoverflow.com/questions/1208853/how-to-call-c-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!