静态库实现
Static library implementation
我正在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类使用了它,但有没有一种方法可以将类包装成用户不知道我使用了什么头等等?我之所以这么问,是因为只给人们一个标题和库,而不是一堆标题会更容易。
更容易[…]拥有UniverseObject 类型的变量
一个"宇宙"是一个eo-ipso的一个候选单光子
universe.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
universe.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.;
}
main.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"对象是根据第一次需求创建的,并且在程序终止时也会被清理。
相关文章:
- 使用本机 JNI 静态方法实现C++ Java 运行时错误
- 如何在基类中定义静态接口,并确保该接口必须在派生类中实现
- C++ 入门 12.1:我可以在类中使用静态向量成员实现 StrBlob<string> 吗?
- 调用没有主体的未实现静态方法
- std::add_pointer 非静态成员函数的实现
- 函数内具有静态变量的单例类(迈耶实现)
- 共享库链接到具有通用接口但不同实现的静态库
- 具有依赖于实现的成员函数类型的多个静态接口
- C++ 线程函数指针实现返回错误无效使用非静态成员函数
- 在C 上实现静态数据成员
- C 从实现文件中访问私有静态成员
- 如何使用C 实现虚拟静态行为
- 在 C++ 中实现静态变量的访问器
- 在可执行文件中实现静态方法是否安全,该方法已在共享库中实现
- 在 c++ 中实现静态构造函数不起作用
- 如何在c++中实现静态工厂模式
- 关于实现静态成员函数模板时重定义错误的c++问题
- 如何实现静态虚成员函数
- C++Singleton实现-静态问题
- 在C++上实现静态强制转换