C++:使类及其某些数据成员仅在 namespace 中可用

标签 c++ scope namespaces member

是否可以让一个类只在命名空间内可用?还是有另一种方式,不使用命名空间? 我正在努力创建一个框架,但不希望该框架的用户可以访问所有类,而只能访问特定类。

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

这可能吗?

示例(只是对我的请求的解释):

/* 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 idiom :

"Pointer to implementation" or "pImpl" is a C++ programming technique that removes implementation details of a class from its object representation by placing them in a separate class, accessed through an opaque pointer.

关于C++:使类及其某些数据成员仅在 namespace 中可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47042165/

相关文章:

javascript - Mootools 类变量作用域

c++ - c++11 lambda 真的支持闭包吗?函数变量中存在语义冲突

javascript - 全局变量未分配给函数外部。

c# - 命名空间和类同名?

c# - 读取带和不带命名空间标签的节点

c++ - Boost ASIO - 如何编写控制台服务器 2

c++ - 如何推导函数内部 vector 的大小? ( vector 通过指向其第一个元素的指针传递)

c# - 使用指令导入子命名空间

C++ 指针的内存地址和指针数组的内存地址如何相同?

c++ - 带用户输入的参数化构造函数 (C++)