C++:项目相互依赖调用解决方法两种方法

C++:项目相互依赖调用解决方法两种方法_第1张图片

Bmodel依赖于Amodel,但是Amodel又需要BModel的信息。这样就会导致相互依赖。


方法一:采用静态变量static

链接:C++开发中一个解决方案里,两个项目的相互引用,相互依赖的实现方法(解决方法)_Capricorn_L的博客-CSDN博客

 Amodel
OperationUIManager.h

#pragma once

#ifdef AMODEL_EXPORTS
#define AMODEL_API _declspec(dllexport)
#else
#define AMODEL_API _declspec(dllimport)
#endif

class AMODEL_API OperationUIManager
{
public:
	OperationUIManager() {}
protected:
	static OperationUIManager* m_pOperationUIManager;
public:
	//将数据加入到提取的图层
	virtual int Get(int num) = 0;
	static OperationUIManager* GetManager();
};

 OperationUIManager.cpp

#include "pch.h"
#include "OperationUIManager.h"
OperationUIManager* OperationUIManager::m_pOperationUIManager = NULL;
OperationUIManager* OperationUIManager::GetManager()
{
	return m_pOperationUIManager;
}

 Bmodel
DesignUIManger.h

#ifdef BMODEL_EXPORTS
#define BMODEL_API _declspec(dllexport)
#else
#define BMODEL_API _declspec(dllimport)
#endif


class  BMODEL_API DesignUIManger :public OperationUIManager
{
public:
	static DesignUIManger& GetInstance();

private:
	DesignUIManger();
	DesignUIManger(const DesignUIManger&)=delete;
	DesignUIManger& operator=(const DesignUIManger&) = delete;
public:
	virtual int Get(int num);
};

DesignUIManger.cpp 

#include "pch.h"
#include "DesignUIManger.h"

DesignUIManger& DesignUIManger::GetInstance()
{
	static DesignUIManger m_instance;
	return m_instance;
}

int DesignUIManger::Get(int num)
{
	return num * 10;
}

DesignUIManger::DesignUIManger()
{
	OperationUIManager::m_pOperationUIManager = this;
}

DesignUIManger& m_pDesignUIManager = DesignUIManger::GetInstance();

 modelsRelation.cpp (执行 DesignUIManger::GetInstance().Get(10);是为了让程序初始化一下DesignUIManger地址)

C++:项目相互依赖调用解决方法两种方法_第2张图片

方法二:采用函数指针,回调函数

 Amodel

OperationUIManager.h

#include 
#ifdef AMODEL_EXPORTS
#define AMODEL_API _declspec(dllexport)
#else
#define AMODEL_API _declspec(dllimport)
#endif

using Getfun = std::function;

extern "C"	//以"C"的方式导出接口
{
	extern AMODEL_API Getfun GetCurDb;
}

 OperationUIManager.cpp

#include "OperationUIManager.h"

Getfun GetCurDb = nullptr;

  Bmodel
DesignUIManger.h

#include "SingletonInterface.h"

#ifdef BMODEL_EXPORTS
#define BMODEL_API _declspec(dllexport)
#else
#define BMODEL_API _declspec(dllimport)
#endif

BMODEL_API void Init();

 DesignUIManger.cpp

#include "DesignUIManger.h"
#include "../AModel/OperationUIManager.h"

int Get1(int num) { return num * 2; };


void Init()
{
	GetCurDb = Get1;
}

  modelsRelation.cpp (执行 init;是为了让程序初始化一下)

#include 
#include "../AModel/OperationUIManager.h"

#include "../BModel/DesignUIManger.h"
using namespace std;
int main()
{
    Init();
    if (GetCurDb)
    {
		cout << GetCurDb(10) << endl;
    }
}

 C++:项目相互依赖调用解决方法两种方法_第3张图片

你可能感兴趣的:(C++经验,c++)