gpt4 book ai didi

c++ - 静态库实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:15:42 26 4
gpt4 key购买 nike

我正在用 C++ 实现一个静态库。我遇到的问题是在库附带的头文件中包含其他头文件。如何包装库以使这些文件不可见?例如,假设我有这段代码:

//MyLib.h
#ifndef MyLib_h
#define MyLib_h
class Math
{
public:
// this method returns the mass of the Universe
static double CalcMassOfTheUniverse();
}
#endif

//MyLib.cpp
#include MyLyb.h
double Math::CalcMassofTheUniverse()
{
// do some complicated calculations here
return result;
}

然后我发现为了更容易地计算宇宙的质量,我必须有一个 UniverseObject 类型的变量:

//MyLib.h
#ifndef MyLib_h
#define MyLib_h
#include "UniverseObject.h"
class Math
{
public:
double string CalcMassOfTheUniverse();
private:
UniverseObject m_Universe; // used to calculate the mass
}
#endif

//MyLib.cpp
#include MyLib.h
double Math::CalcMassofTheUniverse()
{
// Use m_Universe to calculate mass of the Universe
return massOfTheUniverse;
}

问题是现在我在头文件中包含“UniverseObject.h”。我知道这是必要的,因为 Math 类使用它但是有没有办法以用户不知道我使用什么标题等的方式包装类?我问这个是因为只给人们一个标题和库而不是一堆标题会更容易。

最佳答案

easier [...] to have a variable of type UniverseObject

“宇宙”是一个 eo ipso 是 Singleton 的候选者

宇宙.h:

#ifndef UNIVERSE_H
#define UNIVERSE_H 1

// Singleton pattern
class Universe {
public:
static Universe& instance() noexcept {
static Universe universe; // there shall be light
return universe; // now there is light; that's good
}

double guess_total_energy() const noexcept;

private:
Universe() noexcept;
~Universe() noexcept;

Universe(const Universe&) = delete;
Universe(Universe&&) = delete;
Universe& operator=(const Universe&) = delete;
Universe& operator=(Universe&&) = delete;
};
#endif // ifndef UNIVERSE_H

宇宙.c++:

#include <iostream>
#include "universe.h"

Universe::Universe() noexcept {
std::cout << "BANG! (Universe constructor called)"
<< std::endl;
}

Universe::~Universe() noexcept {
std::clog << "Universe destructor called."
<< std::endl;
}

double
Universe::guess_total_energy() const noexcept {
return 0.;
}

主.c++:

#include <iostream>
#include "universe.h"

int main() {
std::cout << "In the beginning..." << std::endl;

// or whereever you need that instance
Universe& universe = Universe::instance();

std::cout << std::scientific
<< universe.guess_total_energy() << "J guessed"
<< std::endl;

return 0; // EXIT_SUCCESS;
}

编译:

g++-4.9 -std=c++11 -Wall -pedantic  main.c++ universe.c++
./a.out

输出:

    In the beginning...
BANG! (Universe constructor called)
0.000000e+00J guessed
Universe destructor called.

正如您可能从输出中看到的那样,“Universe”对象是在第一次需要时创建的,并且也在程序终止时被清除。

关于c++ - 静态库实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33897702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com