C++二进制文件保存数据 类与结构体的区别

C++二进制文件保存数据 类与结构体的区别

运行如下测试代码:

// OS: Ubuntu 19.10
// gcc version 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2)

#include 
#include 
#include 
#include 

using std::string;
using std::ofstream;
using std::cout;
using std::cerr;
using std::endl;
using std::ios;

class Test {
private:
    int value;
    int data;
public:
    Test() { value = 0; data = 0; }
    Test(int num1, int num2) : value(num1), data(num2) {}
    void show() { cout << value << ' ' << data << endl; }
    int getValue() const { return value; }
    int getData() const { return data; }
    void setValue(int num) { value = num; }
    void setData(int num) { data = num; }
};

struct TestSt {
    int value;
    int data;
};

int main(int argc, char const *argv[])
{
    const string file_path_class = "/home/aimerneige/temp/class.aimt";
    const string file_path_struct = "/home/aimerneige/temp/struct.aimt";

    Test t(15, 255);
    TestSt ts = {15, 255};

    ofstream outfile_class(file_path_class, ios::binary);
    if (!outfile_class) {
        cerr << "Can't open the file outfile_class" << endl;
        exit(1);
    }
    else {
        cout << "Open outfile_class success!" << endl;
    }
    outfile_class.write((char *) &t, sizeof(t));
    outfile_class.close();

    ofstream outfile_struct(file_path_struct, ios::binary);
    if (!outfile_struct) {
        cerr << "Can't open the file outfile_struct" << endl;
        exit(1);
    }
    else {
        cout << "Open outfile_struct success!" << endl;
    }
    outfile_struct.write((char *) &ts, sizeof(ts));
    outfile_struct.close();

    return 0;
}

// The file in disk are same.

使用GHex打开生成的文件,内容完全相同。

故使用类来保存数据并不会产生额外的内容。

你可能感兴趣的:(C++,c++)