拆分C ++类声明 [英] Split a C++ class declaration
本文介绍了拆分C ++类声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道我是否可以拆分C ++类声明
I want to know if I can split a C++ class declaration
原始班级
class P
{
private:
int id;
//some really secret method
int secretMethod();
protected:
int x;
public:
P();
int getX();
};
我只想在.h中显示公共的和受保护的方法和属性,并在其他地方声明私有的,而类的用户看不到它.
I want to show in the .h only the public and protected method and attributes, and declare somewhere else the private, where the user of the class can't see it.
想要的类声明:
class P
{
protected:
int x;
public:
P();
int getX();
};
我想要这样做:
- 我可以更改类的实现,并且该类的用户是透明的
- 对于用户来说,查看更少的信息要比查看更多的信息更容易
- 如果我更改类的实现,请更改我不想为类用户更改.h的私有属性和方法
推荐答案
是的,有可能但不是直接的方式.这是您的工作:
Yes, it is possible but not in the direct kind of way. Here is what you do:
my_object.h:
my_object.h:
struct my_object {
void fun();
my_object();
my_object(my_object const&);
~my_object();
my_object& operator = (my_object);
protected:
void pfun();
private:
struct impl;
std::unique_ptr<impl> pimpl;
};
my_object.cpp:
my_object.cpp:
struct my_object::impl {
void fun() { do stuff...}
void pfun() { do other stuff... }
int private_member;
};
my_object::my_object() : pimpl(new impl) {}
my_object::my_object(my_object const& o) : pimpl(new impl(*o.pimpl) {}
my_object::~my_object() {}
my_object& my_object::operator = (my_object o) { swap(pimpl, o.pimpl); return *this; }
void my_object::fun() { pimpl->fun(); }
void my_object::pfun() { pimpl->pfun(); }
如您所见,这需要大量工作,并且需要堆.平衡的一切……在需要时使用.
As you can see, it's a lot of work and requires the heap. Everything in balance...use when you need to.
这篇关于拆分C ++类声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文