c++ - 带有类的库如何工作?

标签 c++ libraries

在学校学习 C++ 时,我们从未真正讨论过如何构建库,很抱歉我的初步理解。 从我在网上阅读的内容来看,库似乎只是已经编译过的代码的集合,然后有一个 .h。列出该库中可访问的函数的文件。

例如当我 #include <cmath>我现在可以调用 sin(x)无需访问 cmath 代码即可对其进行编译。我的问题是这是否适用于其中包含数据的类。

那么我可以创建一个库吗

//AccumulatorLibrary.h
class Accumulator
{
public:
    int num;
    int increment() {num++};
    void otherFunctions(); //otherFunctions defined in the .lib file
}

然后调用它

//Main
#include "AccumulatorLibrary.h"
#include <stdio>
int main()
{
    Accumulator A(0); //initalize num to 0
    Accumulator B(7); //initalize num to 7
    cout<<A.increment;
    cout<<B.increment;
    cout<<A.increment;
}

并得到 1 8 2 的输出?

总而言之,如果我弄清楚如何将一堆类放入库文件中,我就可以访问我想要的任何数据,只要该数据在 .h 中具有访问函数即可。文件?

或者更基本的问题,做一个.h.lib文件的工作方式与常规 C++ 代码完全相同,只是在使用时无需编译,并且您无权访问 .lib 中的代码。文件?

最佳答案

From what I've read online, it seems like a library is just a collection of code that is already compiled, and then there is a .h file that lists what functions are accessible in that library.

正确。

My question is if this works with classes that have data in them.

确实如此。许多 C++ 库公开类并将其代码预编译在库中。

Or a more basic question, do a .h and .lib file work exactly the same as regular c++ code except that it doesn't have to be compiled when you use it...

等等等等。 .h 文件仍然包含 C++ 代码(声明,有时甚至是内联实现)。 .lib 文件是动态链接库。它们是 C++ 源文件编译(和链接)的结果。

...and you don't have access to the code in the .lib file?

您确实可以访问它:使用反汇编程序打开它。它不再是 C++。

关于c++ - 带有类的库如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840553/

相关文章:

c++ - 使用 pushButton 保存 QListWidget 项目

c++ - 为特定类型的所有应用程序创建一个基类是好的设计吗?

c++ - 在线性时间内使用邻接表创建顶点对

javascript - C++ 使用批处理脚本清除所有浏览器 cookie

java - 为什么 Sparkjava 不适合生产?

c++ - 如何借助 SWIG 在 Go 代码中使用 C++ 共享库?

pointers - 如何在 Go 中引用具有相同功能的多个库并在它们之间内联切换

c++ - Windows.h输入

c++ - 多个 Dll 通过 "main"dll 相互调用函数

c# - 使 .net 框架库可再分发