C++中的静态方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5980520/
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
Static methods in C++
提问by ABV
I am having a little trouble working with static methods in C++
我在使用 C++ 中的静态方法时遇到了一些麻烦
Example .h:
示例.h:
class IC_Utility {
public:
IC_Utility();
~IC_Utility();
std::string CP_PStringToString( const unsigned char *outString );
void CP_StringToPString( std::string& inString, unsigned char *outString, short inMaxLength );
static void CP_StringToPString( std::string& inString, unsigned char *outString);
void CP_StringToPString( FxString& inString, FxUChar *outString);
};
Example .cpp:
示例.cpp:
static void IC_Utility::CP_StringToPString(std::string& inString, unsigned char *outString)
{
short length = inString.length();
if( outString != NULL )
{
if( length >= 1 )
CPLAT::CP_Utility::CP_CopyMemory( inString.c_str(), &outString[ 1 ], length );
outString[ 0 ] = length;
}
}
I wanted to make a call like:
我想拨打这样的电话:
IC_Utility::CP_StringToPString(directoryNameString, directoryName );
But I get an error:
但我收到一个错误:
error: cannot declare member function 'static void IC_Utility::CP_StringToPString(std::string&, unsigned char*)' to have static linkage
I dont understand why I cannot do this. Can anyone help me understand why and how to achieve what I want?
我不明白为什么我不能这样做。谁能帮助我理解为什么以及如何实现我想要的?
回答by x13n
Remove static
keyword in method definition. Keep it just in your class definition.
删除static
方法定义中的关键字。将它保留在您的类定义中。
static
keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.
static
放在 .cpp 文件中的关键字意味着某个函数具有静态链接,即。它只能从同一文件中的其他函数访问。
回答by Bo Persson
Keywords static
and virtual
should not be repeated in the definition. They should only be used in the class declaration.
关键字static
和virtual
不应在定义中重复。它们应该只在类声明中使用。
回答by cpx
You don't need to have static
in function definition
你不需要static
在函数定义中
回答by Prince Aloies
Static member functions must refer to static variables of that class. So in your case,
静态成员函数必须引用该类的静态变量。所以在你的情况下,
static void CP_StringToPString( std::string& inString, unsigned char *outString);
Since your member function CP_StringToPstring
is static, the parameters in that function, inString
and outString
should be declared as static too.
由于您的成员函数CP_StringToPstring
是静态的,该函数中的参数inString
也outString
应声明为静态。
The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.
静态成员函数不引用它正在处理的对象,但您声明的变量引用其当前对象,因此返回错误。
You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.
您可以从成员函数中删除静态或添加静态,同时将用于成员函数的参数也声明为静态。