是否可以使一个类仅在命名空间内可用?或者是否有其他方式,而不使用命名空间? 我正在努力创建一个框架,并且不希望这个框架的用户能够访问所有类,只能访问特定的类。
但是:用户应该能够达到所有定义,以便为这些类创建指针变量。此外,他不应该能够访问这些类的所有数据成员,但我希望我的框架能够访问所有数据成员。
这甚至可能吗?
示例(仅作为我的请求的解释):
/* T2DApp.h */
namespace T2D {
// I don't want the user to be able to create an instance of this class (only pointer vars), but the framework should be able to.
class T2DApp {
public:
// constructor, destructor... //
SDL_Window* Window;
SDL_Surface* Surface;
bool Running = false;
}
}
/* T2D.h */
#include "T2DApp.h"
void init();
/* T2D.cpp */
#include "T2D.h"
void init() {
T2D::T2DApp app; // function in framework is able to create new instance of T2DApp.
app.Window.Whatever(); // every data member should be available to framework directly without getter methods.
app.Window.Whatever(); // dito
app.Running = true; // dito
}
/* [cpp of user] */
#include "T2D.h"
void main(etc.) {
...
T2D::T2DApp app; // User shouldn't be able to create an instance of T2DApp
T2D::T2DApp* p_app; // but he should still be able to "see" the class definition for creating pointers
...
p_app.Running = true; // User shouldn't be able to access this data member
p_app.Window.Whatever(); // But he should be able to access the other data members
p_app.Surface.Whatever(); // dito
...
}
非常感谢您提前:))
答案 0 :(得分:0)
可以使用Pimpl
idiom:
“指向实现的指针”或“pImpl”是一种C ++编程技术,它通过将类放在一个单独的类中,通过不透明的指针访问它,从而将类的实现细节从其对象表示中删除。