我编写了一个简单的 C++ 类程序来读取和/或打印一些 BMP 头信息,如下所示,它工作得很好。但是,我想利用 C++ 构造函数初始化程序可以提供的优势。因此,我想使用 C++ 构造函数初始化程序来打开文件并检索数据,即 mOffBits、mWidth 和 mHeight。这可能吗?
头文件:
#include <fstream>
#include <iostream>
#include <string>
class BMP
{
public:
BMP (const std::string& inFileName);
~BMP ();
const void printInfo () const;
private:
std::ifstream ifs;
std::string mInFileName;
std::uint32_t mOffBits;
std::int32_t mWidth, mHeight;
char str [54];
};
程序文件:
#include "bmp.h"
BMP::BMP (const std::string& inFileName) : mInFileName (inFileName)
{
ifs.open (mInFileName, std::ios::in | std::ios::binary);
ifs.seekg (0, std::ios::beg);
ifs.read (&str [0], 54);
mOffBits = *reinterpret_cast <std::uint32_t*> (&str [0xA]);
mWidth = *reinterpret_cast <std::int32_t*> (&str [0x12]);
mHeight = *reinterpret_cast <std::int32_t*> (&str [0x16]);
}
BMP::~BMP ()
{
ifs.close ();
}
const void BMP::printInfo () const
{
std::cout << "\tInput filename:\t\t" << mInFileName << std::endl;
std::cout << "\tBegin of IMG data:\t" << mOffBits << std::endl;
std::cout << "\tHeight:\t\t\t" << mHeight << std::endl;
std::cout << "\tWidth:\t\t\t" << mWidth << std::endl;
}
主.cpp:
#include "bmp.h"
auto main (int argc, char* argv []) -> int
{
if (argc < 2)
{
std::cout << argv [0] << " image.bmp" << std::endl;
return 1;
}
// Itialize bmp class;
BMP bmp (argv [1]);
// print out header information.
bmp.printInfo ();
return 0;
}