我如何通过公共接口(C++)连接两个类(不认识彼此的类别)
我目前正在从事一个项目,其中一切都与所有内容都充满了混合。每个文件都包括其他文件等。 我想将此意大利面代码的分开部分集中在一个库中,该库必须完全独立于该代码的其余部分。
当前的问题是我库的某些函数函数内部使用某些函数 function external 在其他地方声明,因此我的库包括项目中包含的其他一些文件要求“独立于代码的其余部分”。
不用说,我无法在库中移动功能外部。
解决此问题的第一个想法是实现一个公共界面,例如描述的Bellow:
,
但我可以' t使它起作用。是我的全局模式是我可以实现它的方式,还是在可能的情况下(如果可能)将两个函数接口而不在另一个文件中插入一个函数,从而导致不必要的依赖关系。
我如何抽象我的外部阶级,以便我的库仍然独立于我的代码的其余部分?
编辑1:
外部
#include "lib/InterfaceInternal.h"
class External : public InterfaceInternal {
private:
void ExternalFunction() {};
public:
virtual void InterfaceInternal_foo() override {
ExternalFunction();
};
};
。
#pragma once
#include "InterfaceInternal.h"
class Internal {
// how can i received there the InterfaceInternal_foo overrided in External.h ?
};
#pragma once
class InterfaceInternal {
public:
virtual void InterfaceInternal_foo() = 0;
};
I'm currently working on a project where everything is horribly mixed with everything. Every file include some others etc..
I want to focus a separating part of this spaghetti code into a library which has to be completely independent from the rest of the code.
The current problem is that some functions FunctionInternal of my library use some functions FunctionExternal declared somewhere else, hence my library is including some other files contained in the project, which is not conform with the requirement "independent from the rest of the code".
It goes without saying that I can't move FunctionExternal in my library.
My first idea to tackle this problem was to implement a public interface such as described bellow :
But I can't get it to work. Is my global pattern a way I could implement it or is there another way, if possible, to interface two functions without including one file in another causing an unwanted dependency.
How could I abstract my ExternalClass so my library would still be independent of the rest of my code ?
Edit 1:
External.h
#include "lib/InterfaceInternal.h"
class External : public InterfaceInternal {
private:
void ExternalFunction() {};
public:
virtual void InterfaceInternal_foo() override {
ExternalFunction();
};
};
Internal.h
#pragma once
#include "InterfaceInternal.h"
class Internal {
// how can i received there the InterfaceInternal_foo overrided in External.h ?
};
InterfaceInternal.h
#pragma once
class InterfaceInternal {
public:
virtual void InterfaceInternal_foo() = 0;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以像建议的那样做,覆盖外部代码中的内部接口。然后
只需将指针/引用传递给您的
类外部
,它扩展了类InterfaceInternal
。当然,您的类内部
需要具有接受InterfaceNternal*
的方法。或者,您可以将函数传递到内部界面作为参数。周围的东西:
或更多通用:
You can do like you suggested, override the internal interface in your external code. Then
just pass a pointer/reference to your
class External
that extendsclass InterfaceInternal
. Of course yourclass Internal
needs to have methods that acceptInterfaceInternal*
.Or you can just pass the function to your internal interface as an argument. Something around:
or more generic: