c++ - 如何在不暴露内部结构的情况下与 Pimpl 交换私有(private)数据?

标签 c++ pimpl-idiom

如果您有一个对象 B 需要对象 A 的私有(private)成员的拷贝,并且该私有(private)成员被 Pimpl 隐藏,您如何在不暴露内部结构的情况下实现它? //Foo.h

class Foo
{
private :
  struct impl ;
  impl * pimpl ;
};

// Foo.cpp
struct impl { std::string data; }

//main.cpp
Foo A;
Foo B;
// I want A::pimpl->data copied to B::pimpl->data and I don't want std::string exposed in my Foo header.

最佳答案

// header
class Foo
{
    public:
       void Copy( const Foo & );
    private :
       struct impl ;
       impl * pimpl ;

};

//cpp file
struct impl {std::string data; }

void Foo::Copy( const Foo & f ) {
      pimpl->data = f.pimpl->data;
}

关于c++ - 如何在不暴露内部结构的情况下与 Pimpl 交换私有(private)数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5936752/

相关文章:

c++ - unique_ptr pimpl 和不完整类型

c++ - 使用 PIMPL 习语时,有什么方法可以限制重复的样板文件吗?

c++ - OCCI - setDataBuffer + vector<结构>

C++ : Cannot declare field to be of abstract type

C++ 包含和循环依赖

c++ - 从 Boost 图中删除 100,000 多个节点

c++ - 根据从 Qt 中的 XML 表单中读取的字符串更改 Widget 的名称

类 C 实现的 C++ 等效性能版本

c++ - 如何返回通用迭代器(独立于特定容器)?

c++ - 尝试访问库中成员的功能时出现段错误