有一个私人类型的公共成员有什么意义吗?

发布于 2025-02-04 11:03:29 字数 697 浏览 2 评论 0原文

考虑以下C ++代码,其中Member foo具有私有类型:

class Object {
private:
    struct MyPrivateThing {
        long double Member;
    };
    using Type = MyPrivateThing;
public:
    Type foo = {32.45L};
    // MyPrivateThingFoo also works
};

int main() {
    // Object::Type f = {34.567L}; ERROR: Object::Type is private
    decltype(Object::foo) thingy = {945.67L}; // Fine
    auto x = Object().foo;
    return x.Member * thingy.Member;
}

尽管此代码是合法的C ++并编译了良好的,但似乎有点违反直觉 - Object ::类型是私人的,在班级外不可访问,但是我们仍然可以通过使用auto间接地参考它以获取该类型的变量。

看来,要做的更直接的事情就是让每个公共成员都有公共类型。

您能想到这种模式的任何有效的用例吗?

Consider the following C++ code, where member foo has a private type:

class Object {
private:
    struct MyPrivateThing {
        long double Member;
    };
    using Type = MyPrivateThing;
public:
    Type foo = {32.45L};
    // MyPrivateThingFoo also works
};

int main() {
    // Object::Type f = {34.567L}; ERROR: Object::Type is private
    decltype(Object::foo) thingy = {945.67L}; // Fine
    auto x = Object().foo;
    return x.Member * thingy.Member;
}

Although this code is legal C++ and compiles fine, it seems a bit counter-intuitive —Object::Type is private and not accessible outside the class, yet we can still indirectly refer to it by using auto to get a variable of that type.

It would seem that the more straightforward thing to do would be to just make every public member have a public type.

Can you think of any valid use-cases for this pattern?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文