方法:将A中要被调用的成员函数放入到基类中,并设为虚函数,A作为该基类的派生类
client.h
#pragma once
#include <memory>
#include <iostream>
class base
{
public:
base() {}
virtual ~base() {
}
virtual void doSomething() = 0;
};
class client
{
public:
client(base *p) :m_fatherPtr(p) {}
~client() {
}
void test() { m_fatherPtr->doSomething(); };
base* m_fatherPtr;//注意这里不能用智能指针
};
fahter.h
#pragma once
#include <memory>
#include <iostream>
#include "client.h"
class father:public base
{
public:
father() {
}
~father() {
}
void init()
{
m_clientPtr = std::make_shared<client>(this);
m_clientPtr->test();
}
void doSomething()
{
std::cout << "father do something" << std::endl;
}
private:
std::shared_ptr<client> m_clientPtr;
};
main.cpp
#include "father.h"
int main(int argc, char* argv[])
{
father f;
f.init();
return 0;
}