大佬教程收集整理的这篇文章主要介绍了c – 如何避免#include对外部库的依赖,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
// Myfile.h #include "SomeHeaderFile.h" // External library Class MyClass { // My code };
在我自己的项目中,我可以告诉编译器(在我的情况下,Visual studio)在哪里寻找SomeHeaderFile.h.然而,我不希望我的用户关心这一点 – 他们应该能够包含我的标题,而不必通知他们的编译器SomeHeaderFile.h的位置.
这种情况如何正常处理?
>从外部库转发声明所需的任何类或函数.然后将外部库的头文件仅包含在您的cpp文件中(当您实际需要使用您的头文件中转发的类或函数时).
>使用您转发的PImpl成语(或Cheshire Cat),声明一个“私有”(在cpp文件中)声明和定义的“实现”类.您使用该私有类来放置所有与外部程序库相关的代码,以避免在您的公共类(在您的头文件中声明的那个)中有任何痕迹.
#ifndef MY_LIB_MY_HEADER_H #define MY_LIB_MY_HEADER_H class some_external_class; // forWARD-declare external dependency. class my_class { public: // ... void someFunction(some_external_class& aRef); // declare members using the forWARD-declared incomplete type. }; #endif // in the cpp file: #include "my_header.h" #include "some_external_header.h" void my_class::someFunction(some_external_class& aRef) { // here,you can use all that you want from some_external_class. };
以下是选项2的示例:
#ifndef MY_LIB_MY_HEADER_H #define MY_LIB_MY_HEADER_H class my_class_impl; // forWARD-declare private "implementation" class. class my_class { private: std::unique_ptr<my_class_impl> pimpl; // a vanishing facade... public: // ... }; #endif // in the cpp file: #include "my_header.h" #include "some_external_header.h" class my_class_impl { private: some_external_class obj; // ... public: // some functions ... }; my_class::my_class() : pimpl(new my_class_impl()) { };
以上是大佬教程为你收集整理的c – 如何避免#include对外部库的依赖全部内容,希望文章能够帮你解决c – 如何避免#include对外部库的依赖所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。