C++ 我在哪里可以定义私有函数的主体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3069801/
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
Where can I define the body for a private function?
提问by Martijn Courteaux
I have a header like this (header guards not shown):
我有一个这样的标题(未显示标题守卫):
class GameSystem
{
public:
GameSystem(Game *pcGame);
virtual ~GameSystem();
void Setup();
private:
void InitGame();
void RunGame();
void ExitGame();
Game *m_pcGame;
/* Properties */
int m_nWidth;
int m_nHeight;
int m_nFps;
bool m_bFullscreen;
};
Where can I define the body for InitGame()
, RunGame()
and ExitGame()
? Can I define it in my .cpp
file? If so, how? Or am I obliged to make their body in my .h
file?
我可以在哪里定义InitGame()
,RunGame()
和的主体ExitGame()
?我可以在我的.cpp
文件中定义它吗?如果是这样,如何?还是我有义务将他们的尸体放在我的.h
档案中?
I'm using Eclipse and I began typing: void GameSystem::
and then it doesn't suggest the private functions.
我正在使用 Eclipse 并开始输入:void GameSystem::
然后它不建议私有函数。
回答by wheaties
Yes, you can define then in a .cpp file. Just put #include "MyHeader.h"
at the beginning of the file. You'll also need to start each function like so
是的,您可以在 .cpp 文件中定义。放在#include "MyHeader.h"
文件的开头就行了。您还需要像这样启动每个功能
void GameSystem::Init(){
//stuff
}
回答by Artelius
Generally you would define both public andprivate functions in the .cpp
file.
通常,您会在文件中定义公共和私有函数.cpp
。
One reason to define functions in the .h
file is if you want them to be inlineable.
在.h
文件中定义函数的原因之一是希望它们可内联。
回答by ur.
I think you are concerned about private
functions should be private with the meaning of "not visible in the header (which is the interface)".
But private
means "not accessible from outside the class", i.e. only functions of the class can call private
functions.
If you don't want (human) users of your class see these implementation details, you need to use a suitable design patterns (facade pattern e.g.).
我认为您担心private
函数应该是私有的,意思是“在标题(即接口)中不可见”。但是private
意味着“不能从类外部访问”,即只有类的private
函数才能调用函数。如果您不希望类的(人类)用户看到这些实现细节,则需要使用合适的设计模式(例如外观模式)。
回答by rhapsodyn
Defining in .h
means inline, but defining in .cpp
and using forward declaration, you can make your compilation more efficient.
定义 in.h
意味着内联,但定义 in.cpp
并使用前向声明,可以使编译更高效。