C++ 静态函数:这里可以不指定存储类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15725922/
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 function: a storage class may not be specified here
提问by sccs
I have defined a function as static in my class in this manner (snippet of relevant code)
我以这种方式在我的班级中将一个函数定义为静态(相关代码片段)
#ifndef connectivityClass_H
#define connectivityClass_H
class neighborAtt
{
public:
neighborAtt(); //default constructor
neighborAtt(int, int, int);
~neighborAtt(); //destructor
static std::string intToStr(int number);
private:
int neighborID;
int attribute1;
int attribute2;
#endif
and in the .cpp file as
并在 .cpp 文件中作为
#include "stdafx.h"
#include "connectivityClass.h"
static std::string neighborAtt::intToStr(int number)
{
std::stringstream ss; //create a stringstream
ss << number; //add number to the stream
return ss.str(); //return a string with the contents of the stream
}
and I get an error (VS C++ 2010) in the .cpp file saying "A storage class may not be specified here" and I cannot figure out what I'm doing wrong.
我在 .cpp 文件中收到一个错误(VS C++ 2010),提示“此处可能未指定存储类”,我无法弄清楚我做错了什么。
p.s. I've already read thiswhich looks like a duplicate but I don't know - as he does - that I am right and the compiler is being finicky. Any help is appreciated, I can't find any information on this!
ps 我已经读过这个看起来像是重复的,但我不知道 - 正如他所做的那样 - 我是对的,编译器很挑剔。任何帮助表示赞赏,我找不到任何有关此的信息!
回答by Adam Rosenfield
In the definition in the .cpp
file, remove the keyword static
:
在.cpp
文件的定义中,删除关键字static
:
// No static here (it is not allowed)
std::string neighborAtt::intToStr(int number)
{
...
}
As long as you have the static
keyword in the header file, the compiler knows it's a static class method, so you should not and cannot specify it in the definition in the source file.
只要你static
在头文件中有关键字,编译器就知道它是一个静态类方法,所以你不应该也不能在源文件的定义中指定它。
In C++03, the storage class specifiersare the keywords auto
, register
, static
, extern
, and mutable
, which tell the compiler how the data is stored. If you see an error message referring to storage class specifiers, you can be sure it's referring to one of those keywords.
在C ++ 03中,存储类声明是关键字auto
,register
,static
,extern
,和mutable
,它告诉编译器的数据存储方式。如果您看到有关存储类说明符的错误消息,您可以确定它指的是这些关键字之一。
In C++11, the auto
keyword has a different meaning (it is no longer a storage class specifier).
在 C++11 中,auto
关键字具有不同的含义(它不再是存储类说明符)。