gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:42:26 36 4
gpt4 key购买 nike

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

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

这可能吗?

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

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

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com