C++ Pimpl技法 C++接口实现分离原理

C++Pimpl技法

优点

  1. 将C++的接口和实现分离在两个类中
  2. C++的实现和接口在不同的文件中,实现改变不会导致接口文件重新编译

将下面的代码分开在几个文件里面就实现了Pimpl技法

#include <iostream>

class X;

class C

{

public:

    C();

    virtual ~C();

    void Fun();

private:

    std::auto_ptr<X> pImpl_; //pimpl

};

 

class X

{

public:

    X()

    {

        printf("new x\n");

    }

    virtual ~X()

    {

        printf("delete X\n");

    }

    void Fun()

    {

    }

};

C::C():pImpl_(new X)

{

    printf("new C\n");

}

C::~C()

{

    printf("delete C\n");

}

void C::Fun()

{

    pImpl_->Fun();

}

 

 

int main()

{

    std::auto_ptr<C> c(new C);

    c->Fun();

    return 0;

}

 

猜你喜欢

转载自blog.csdn.net/qq_28437139/article/details/83870368