C++ 如何调用C++静态方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1208853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call C++ static method
提问by Paul
Is it possible to return an object from a static method in C++ like there is in Java? I am doing this:
是否可以像在 Java 中一样从 C++ 中的静态方法返回对象?我正在这样做:
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 类中只有静态方法,因此实例化它没有意义。但我得到这个编译错误:
MyMath.cpp:69: error: expected primary-expression before '.' token
MyMath.cpp:69: 错误:'.' 之前的预期主表达式 令牌
What am I doing wrong? Do I haveto instantiate MyMath? I would rather not, if it is possible.
我究竟做错了什么?我必须实例化 MyMath 吗?如果可能的话,我宁愿不这样做。
回答by Paul
Use ::
instead of .
使用::
代替.
MyObject o = MyMath::calcSomething();
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();
回答by John Rasch
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?
我必须实例化 MyMath 吗?
No.
不。
回答by Michael Kohne
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.
对于这种情况,您需要 MyMath::calcSomething()。这 '。' 语法用于调用对象中的函数。:: 语法用于调用类或命名空间中的函数。
回答by Marten
Call MyMath::calcSomething()
称呼 MyMath::calcSomething()
回答by Tunvir Rahman Tusher
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
谢谢