等同于C ++中的Java静态方法 [英] Equivalent of Java static methods in C++
本文介绍了等同于C ++中的Java静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在一个C ++类中创建一个方法,可以在不创建该类的实例(像Java中的静态方法)的情况下调用,但我一直遇到此错误: error :
I'm trying to create a method in a C++ class that can be called without creating an instance of the class (like a static method in Java), but I keep running into this error: error: expected unqualified-id before ‘.’ token
这里是我想要编译的.cpp文件:
Here's the .cpp file I'm trying to compile:
using namespace std;
#include <iostream>
class Method {
public:
void printStuff(void) {
cout << "hahaha!";
}
};
int main(void){
Method.printStuff(); // this doesn't work as expected!
return 0;
}
推荐答案
>
In C++ it's
Method::printStuff();
,您必须将方法声明为 static
。
and you have to declare the method as static
.
class Method{
public:
static void printStuff(void){
cout << "hahaha!";
}
};
::
范围解析操作符。你可以调用。
如果它在一个类实例,但实例不是必需的(它是静态和所有...)。
::
is called the scope resolution operator. You can call the method with .
if it's on a class instance, but the instance is not required (it being static and all...).
这篇关于等同于C ++中的Java静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文