在班上隐藏私人会员的最佳方法

Best way to hide private members in a class

本文关键字:最佳 方法 隐藏      更新时间:2023-10-16

我在标头文件中具有以下代码

class Bar {
   public: 
      void public_foo();
   private:  
      void private_foo();
};

该实现隐藏在源文件中

void Bar::public_foo(){
   private_foo();
}
void Bar::private_foo(){
   // Some more stuff
}

我希望在标题文件中看到私有功能。做这个的最好方式是什么?我知道两种方法:

1(使private_foo像这样的非会员函数

void private_foo(Bar* this){ /* ... */ }

并将其称为public_fooprivate_foo(this)。这对我来说不是很吸引人,因为它不是特别的编程。

2(使用隐藏的实现类

// In header
class Bar {
   public: 
      virtual void public_foo();
      virtual ~Bar() { };
};
Bar* CreateBar();
// In Source
class Bar_impl : public Bar {
   public:
      void public_foo();
   private:  
      void private_foo();
};
Bar* CreateBar(){
    return new Bar_impl;
}
void Bar::public_foo(){
   private_foo();
}
void Bar::private_foo(){
    // Some more stuff
}

这有效,但是对于如此简单的东西来说,这太多了。

是否有第三种(更好的(方法?

编辑:响应@jdehesa,并且由于我喜欢戴上语言设计师的帽子,这是我理想的语法(不正确的C 语法,但可以做梦(

// In header
class Bar {
   public: 
      void public_foo();
};
// In Source
classdef Bar {   // Notice my new "classdef" keyword
public: 
   void public_foo(){
   }
private:
   void private_foo(){
   }
};

一个问题是,对于正确的内存分配,实现类无法添加额外的变量(公共或私有变量(。

您可以使用pimpl成语

示例:

// Pimpl idiom - basic idea
class widget {
    // :::
private:
    struct impl;        // things to be hidden go here
    impl* pimpl_;       // opaque pointer to forward-declared class
};