私有/公共标头示例?
谁能给我一个公共和私人标题如何工作的例子?我在网上做了一些阅读,但我似乎无法通过示例代码找到很多有用的信息.有人建议我应该使用私有标头来分隔代码的公共和私有部分以创建静态库.经过一番阅读,我对它的工作原理有了一个大致的了解,但我真的很感激有一个很好的例子来帮助我入门.具体来说,我不太明白的是如何将接口函数放在我的公共头文件中,而将私有变量/函数放在我的私有头文件中?谢谢!
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:
// 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.
相关文章