是否可以在 * . cpp 文件中实现 static类成员函数而不是 它在头文件?
static
所有的 static函数都是 inline吗?
inline
试试这个:
标题.hxx:
class CFoo { public: static bool IsThisThingOn(); };
Cxx:
#include "header.hxx" bool CFoo::IsThisThingOn() // note: no static keyword here { return true; }
是的。关键是只在 标题文件中使用 static关键字,在源文件中使用 没有!
Hpp:
class A { public: static int a(int i); // use `static` here };
Cpp:
#include <iostream> #include "test.hpp" int A::a(int i) { // do **not** use `static` here! return i + 2; } using namespace std; int main() { cout << A::a(4) << endl; }
它们并不总是内联的,不,但是编译器可以创建它们。
是的,可以在 * 中定义静态成员函数。Cpp 文件。如果您在标头中定义它,编译器将默认将其视为内联的。但是,这并不意味着静态成员函数的单独副本将存在于可执行文件中。请点击这个帖子了解更多信息: C + + 中的静态成员函数是否在多个翻译单元中复制?
helper.hxx
class helper { public: static void fn1 () { /* defined in header itself */ } /* fn2 defined in src file helper.cxx */ static void fn2(); };
helper.cxx
#include "helper.hxx" void helper::fn2() { /* fn2 defined in helper.cxx */ /* do something */ }
A.cxx
#include "helper.hxx" A::foo() { helper::fn1(); helper::fn2(); }
要了解更多关于 c + + 如何处理静态函数的信息,请访问: C + + 中的静态成员函数是否在多个翻译单元中复制?
#include指令的字面意思是“将该文件中的所有数据复制到此点”所以当你包含头文件的时候,它在代码文件的文本中,当代码文件(现在称为 编译单元或 翻译小组)从预处理器模块传递到编译器模块的时候,它里面的所有东西都会在那里,给予或取得其他指令或宏替换的效果。
#include
这意味着静态成员函数的声明和定义实际上一直都在同一个文件中..。
@ crobar,你说得对,多文件示例的确很缺乏,所以我决定分享以下内容,希望能对其他人有所帮助:
:::::::::::::: main.cpp :::::::::::::: #include <iostream> #include "UseSomething.h" #include "Something.h" int main() { UseSomething y; std::cout << y.getValue() << '\n'; } :::::::::::::: Something.h :::::::::::::: #ifndef SOMETHING_H_ #define SOMETHING_H_ class Something { private: static int s_value; public: static int getValue() { return s_value; } // static member function }; #endif :::::::::::::: Something.cpp :::::::::::::: #include "Something.h" int Something::s_value = 1; // initializer :::::::::::::: UseSomething.h :::::::::::::: #ifndef USESOMETHING_H_ #define USESOMETHING_H_ class UseSomething { public: int getValue(); }; #endif :::::::::::::: UseSomething.cpp :::::::::::::: #include "UseSomething.h" #include "Something.h" int UseSomething::getValue() { return(Something::getValue()); }
在头文件中说 呃
class Foo{ public: static void someFunction(params..); // other stuff }
在实现文件中输入 Foo.cpp
#include "foo.h" void Foo::someFunction(params..){ // Implementation of someFunction }
在实现实现文件中的静态函数时,只需确保不在方法签名中使用 static 关键字。
祝你好运