c++ - 一个类在 C++ 中只包含(默认情况下)私有(private)成员有什么用处?

标签 c++ class private private-members private-methods

类的成员在 C++ 中默认是私有(private)的。

因此,我想知道是否有可能使用创建一个将其所有成员(变量和函数)默认设置为私有(private)的类。

换句话说,是否存在任何没有任何关键字publicprotectedprivate的有意义的类定义?

最佳答案

有一种模式,用于访问保护,基于这种类:有时称为 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/

相关文章:

c++ - 模板函数重载 : enable_if for CRTP, 编译器坚持选择泛型函数

python-3.x - 为什么 private __var 可以在类之外改变? (Python 3)

c++ - 仅在特定类型的数组中添加模板化参数

java - 在主类方法中找不到字符串方法

python - 类在 2.4 中不起作用

javascript - 如何从两个可用的 jQuery 中获得二等奖

swift - 在专用 Pod 上执行 lint 命令时出错 "Encountered an unknown error (no implicit conversion of nil into String) during validation."

c++ - 击败 C++ 访问资格的最干净方法是什么?

c++ - 如何使用命名共享内存?

c++ - 创建一个可以在 Visual Studio 2015 中添加引用的属性表