问题描述
有人可以给我一个公共和私有头文件如何工作的例子吗?我已经在网上进行了一些阅读,但似乎找不到包含示例代码的有用信息。有人建议我使用私有头将代码的公共部分和私有部分分开,以创建静态库。阅读一番之后,我对它的工作原理有了一个大致的了解,但真的很感谢一个很好的例子让我入门。具体来说,我不太了解如何将接口函数放在公共标头中,而如何将私有变量/函数放在私有标头中?谢谢!
Can someone please give me an example of how public and private headers work? I have done some reading on the net but I can't seem to find much useful information with sample codes. I was advised that I should use private headers to separate the public and private parts of my code for creating a static library. After some reading I have a general idea of how it works, but would really appreciate a good example to get me started. Specifically, what I don't quite understand is how to put the interface functions in my public header, and the private variables/functions in my private header? Thanks!
编辑:
也许我不是在说我正确的问题,但是我的意思是,例如,我有myMath.h和myMath.cpp,而myMath.h有:
Maybe I'm not wording my question right, but what I meant is, for example, I have myMath.h and myMath.cpp, and myMath.h has:
class myMath{
public:
void initialise(double _a, double _b);
double add();
double subtract();
private:
double a;
double b;
};
myMath.cpp具有函数的实现。如何使myMath.h仅具有三个公用函数,并在另一个文件(例如myMath_i.h)中定义私有变量,并且这三个文件的方式是在创建静态库之后,用户只需要myMath.h。这也意味着myMath.h不能#include myMath_i.h。就像这样:
And myMath.cpp has the implementations of the functions. How can I make it so that myMath.h only has the three public functions, and the private variables are defined in another file (e.g. myMath_i.h), and these three files are in such a way that after I create a static library, only myMath.h is needed by users. This also means myMath.h cannot #include myMath_i.h. So something like:
myMath.h:
class myMath{
public:
void initialise(double _a, double _b);
double add();
double subtract();
}
和myMath_i.h:
and myMath_i.h:
class myMath{
private:
double a;
double b;
}
当然不可能,因为那样的话我将重新定义类myMath。 ..
Of course that's not possible because then I'll be redefining the class myMath...
推荐答案
您有两个头文件MyClass.h和MyClass_p.h,以及一个源文件:MyClass.cpp。
You have two header files MyClass.h and MyClass_p.h and one source file: MyClass.cpp.
让我们看一下其中的内容:
Lets take a look at what's inside them:
MyClass_p.h:
MyClass_p.h:
// Header Guard Here
class MyClassPrivate
{
public:
int a;
bool b;
//more data members;
}
MyClass.h:
MyClass.h:
// Header Guard Here
class MyClassPrivate;
class MyClass
{
public:
MyClass();
~MyClass();
void method1();
int method2();
private:
MyClassPrivate* mData;
}
MyClass.cpp:
MyClass.cpp:
#include "MyClass.h"
#include "MyClass_p.h"
MyClass::MyClass()
{
mData = new MyClassPrivate();
}
MyClass::~MyClass()
{
delete mData;
}
void MyClass::method1()
{
//do stuff
}
int MyClass::method2()
{
return stuff;
}
将数据保留在MyClassPrivate中并分发MyClass.h。
Keep your data in MyClassPrivate and distribute MyClass.h.
这篇关于私有/公共标题示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!