C++:使类及其某些数据成员仅在命名空间中可用

C++: Make class and some of its data members only available in namespace

本文关键字:命名空间 数据成员 C++      更新时间:2023-10-16

是否可以使类仅在命名空间内可用?或者是否有另一种方法,不使用命名空间?我正在努力创建一个框架,不希望这个框架的用户有权访问所有类,只能访问特定的类。

但是:无论如何,用户应该能够访问所有定义,以创建指向这些类的指针变量。此外,他应该无法访问这些类的所有数据成员,但我希望我的框架可以访问所有数据成员。

这可能吗?

示例(仅作为对我的请求的解释):

/* 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
    ...
}

提前非常感谢:)

Pimpl成语是可能的:

"

指向实现的指针"或"pImpl"是一种C++编程技术,通过将类的实现细节放置在通过不透明指针访问的单独类中,从其对象表示中删除类的实现细节。