サンプルコードは、オンラインのPIMPLクラシックサンプルコードの変更に基づいて、次のとおりです。
- Person.h(外部にリリースされたヘッダーファイル、他のファイルはクライアントに表示されません)
#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
- 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);
}
- PersonImpl.h
#include <iostream>
#include "Person.h"
class PersonImpl {
public:
PersonImpl();
virtual ~PersonImpl();
int fun1(int x, int y, Person *arg);
};
- 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;
}
- 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;
}
結果:
クライアントによって書き換えられたfun2関数が正常に呼び出されました。