How to call C++ static method

前端 未结 5 672
萌比男神i
萌比男神i 2020-12-30 21:15

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 calc         


        
相关标签:
5条回答
  • 2020-12-30 21:21

    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.

    0 讨论(0)
  • 2020-12-30 21:41

    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();
    
    0 讨论(0)
  • 2020-12-30 21:42

    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.

    0 讨论(0)
  • 2020-12-30 21:44

    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

    0 讨论(0)
  • 2020-12-30 21:48

    Call MyMath::calcSomething()

    0 讨论(0)
提交回复
热议问题