PIMPL implementation-through this pointer and interface pure virtual function to achieve client code call

The sample code is as follows, based on the online PIMPL classic sample code modification.

  1. Person.h (header file released externally, other files are not visible to the client)
#ifndef PERSON_H
#define PERSON_H
#include <string>

class PersonImpl;   //前向声明
class Person
{
    
    
public:
    Person();
    virtual ~Person();
    int fun1(int x, int y);
    virtual void fun2() = 0; 

private:
//    class PersonImpl; 声明在类内更好
    PersonImpl *mPersonImpl;
};
#endif // PERSON_H
  1. Person.cpp
#include "Person.h"
#include "PersonImpl.h"

Person::Person() : mPersonImpl(new PersonImpl())
{
    
    
    std::cout << "construct Person" << std::endl;
}

Person::~Person() {
    
    
    delete mPersonImpl;
    mPersonImpl = nullptr;
    std::cout << "deconstruct Person" << std::endl;
}

int Person::fun1(int x, int y)
{
    
    
//    cout<< typeid (this).name() <<endl;	//查看this指针指向对象及地址
//    cout<< this <<endl;
    return mPersonImpl->fun1(x, y, this);
}

  1. PersonImpl.h
#include <iostream>
#include "Person.h"

class PersonImpl {
    
    
public:
    PersonImpl();
    virtual ~PersonImpl();

    int fun1(int x, int y, Person *arg);
};

  1. PesonImpl.cpp
#include "PersonImpl.h"
PersonImpl::PersonImpl()
{
    
    
}
PersonImpl::~PersonImpl()
{
    
    
}
int PersonImpl::fun1(int x, int y, Person *arg)	//相比接口类,实现类多一个接口类指针
{
    
    
    //此时this指针对象是Personmpl,不是Person, 所以要将Peson指针传进来
//    cout<< typeid (this).name() <<endl;  //查看this指针指向对象及地址
//    cout<< this <<endl;
    arg->fun2();
    return x+y;
}
  1. main.cpp
#include <iostream>
#include "Person.h"
using namespace std;

class Test : public Person		//客户端继承调用接口文件
{
    
    
public:
    Test(){
    
    };
    virtual void fun2() override;
};

void Test::fun2()		//客户端重写接口纯虚函数
{
    
    
    //客户端实现代码
    cout<<"Sucess!"<<endl;
}

int main()
{
    
    
    Test test1;
    int ret = test1.fun1(1,2);
    cout<< ret <<endl;
    return 0;
}

Result:
Insert picture description here
The fun2 function rewritten by the client is successfully called.

Guess you like

Origin blog.csdn.net/junh_tml/article/details/115001150