如何在C ++中隐藏类? [英] How can I hide a class in C++?

查看:124
本文介绍了如何在C ++中隐藏类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有2个要显示的类(在给定的头文件中),并且有1个类是它们的祖先,我只希望对前面提到的2个类可见.如何实现在C ++中不可见的此类类功能?

Let's say I have 2 classes that I want to be visible (within a given header file) and one class that is their ancestor, which one I want to be visible only to the previously mentioned two. How can I achieve such class functionality of being invisible in C++?

推荐答案

滥用class充当namespace可以做到这一点.我不推荐这种模式.

Abusing a class to act as a namespace will do this. I do not recommend this pattern.

class hidden_stuff {
private: // hide base from everyone
    struct base {
        // contents
    };
public:
    class derived1;
};
typedef class hidden_stuff::derived1 derived1;

class hidden_stuff::derived1
    : private hidden_stuff::base {}; // private inheritance required
            // or hidden_stuff::base is accessible as derived1::base


real 解决方案(尽管在技术上不能满足问题)

一个更好的解决方案是使用一个明确命名的namespace,例如impl::detail::,这将向用户传达他们不应在其中使用任何类,并停止对重载的任何可能的不良影响或类似的东西.这就是大多数库(甚至是标准库实现)如何从用户隐藏"类的方法.


The real solution (though not technically satisfying the question)

A preferable solution would be to use a clearly-named namespace such as impl:: or detail::, which will convey to users that they shouldn't use any classes inside, and stop any possible undesired effects on overloading or the like. That's how most libraries (even Standard Library implementations) "hide" classes from the user.

这篇关于如何在C ++中隐藏类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆