在C++中使用static关键字

And*_*dry 4 c++ static-methods

我有一个类在myclass.hpp中暴露一个静态函数

class MyClass {
public:
   static std::string dosome();
};
Run Code Online (Sandbox Code Playgroud)

好吧,在myclass.cpp中我应该写什么:这个:

std::string MyClass::dosome() {
   ...
}
Run Code Online (Sandbox Code Playgroud)

或这个:

static std::string MyClass::dosome() {
   ...
}
Run Code Online (Sandbox Code Playgroud)

我想我不应该重复静态关键字......这是正确的吗?

sha*_*oth 10

C++编译器不允许这样:

static std::string MyClass::dosome() {
   ...
}
Run Code Online (Sandbox Code Playgroud)

因为static在函数定义中具有完全不同的东西 - static链接(意味着函数只能从同一个翻译单元调用).

static一个成员函数的声明是不够的.


bdo*_*lan 5

不要重复static关键字.这样做会导致错误.