类的成员在 C++ 中默认是私有(private)的。
因此,我想知道是否有可能使用创建一个将其所有成员(变量和函数)默认设置为私有(private)的类。
换句话说,是否存在任何没有任何关键字public
、protected
或private
的有意义的类定义?
最佳答案
有一种模式,用于访问保护,基于这种类:有时称为 passkey pattern (另见 clean C++ granular friend equivalent? (Answer: Attorney-Client Idiom) 和 How to name this key-oriented access-protection pattern?)。
只有 key 类的 friend 可以访问protectedMethod()
:
// All members set by default to private
class PassKey { friend class Foo; PassKey() {} };
class Bar
{
public:
void protectedMethod(PassKey);
};
class Foo
{
void do_stuff(Bar& b)
{
b.protectedMethod(PassKey()); // works, Foo is friend of PassKey
}
};
class Baz
{
void do_stuff(Bar& b)
{
b.protectedMethod(PassKey()); // error, PassKey() is private
}
};
关于c++ - 一个类在 C++ 中只包含(默认情况下)私有(private)成员有什么用处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25785071/