类对象内存大小节约
  • 板块题目总版
  • 楼主TheSkyFuker
  • 当前回复3
  • 已保存回复3
  • 发布时间2024/4/7 18:02
  • 上次更新2024/4/7 20:12:50
查看原帖
类对象内存大小节约
1274996
TheSkyFuker楼主2024/4/7 18:02

这道题sizeof(prof)标准大小应该是44,但我目前是48,求助大佬,该怎么调整呢

#include <iostream>
#include <string>
using namespace std;

class BirthDate
{
public:
    BirthDate(int y, int m, int d) : year(y), month(m), day(d) {}
    void display()
    {
        cout << "Birthday: " << year << "-" << month << "-" << day << endl;
    }
    void setbirthday(int y, int m, int d)
    {
        year = y, month = m, day = d;
    };

private:
    int year;
    int month;
    int day;
};

class Teacher
{
public:
    Teacher(int id, string nam, char se) : num(id), name(nam), sex(se) {}
    void display()
    {
        cout << "Teacher info: " << num << "/" << name << "/" << sex << endl;
    }

protected:       //*派生类能访问的private  (派生不能直接访问private
    int num;     //?  4 byte
    string name; //?  24 byte
    char sex;    //?  1 byte
    //? 29 -> 40 byte in total
};

class Professor : private Teacher //* 私有继承
{
public:
    Professor(int a, string b, char c, BirthDate d) // todo ____qcodep____
        : Teacher(a, b, c), birthday(d)
    {
    }
    void print()
    {
        cout << name << " is professor whose birthday is ";
        birthday.display();
    }
    void display()
    {
        Teacher::display();
        print();
    }
    void setbirthday(int y, int m, int d)
    {
        birthday.setbirthday(y, m, d);
    }

private:
    BirthDate birthday; //?  12byte
};
// todo ____qcodep____

int main()
{
    int num;
    string name;
    char sex;
    int year, month, day;
    cin >> num >> name >> sex;
    cin >> year >> month >> day;
    Professor prof(num, name, sex, BirthDate(year, month, day));
    prof.display();
    cin >> year >> month >> day;
    prof.setbirthday(year, month, day);
    cout << "\nAfter setbirthday:" << endl;
    prof.display();

    Teacher a(1, name, sex);
    BirthDate b(year, month, day);
    cout << "############ " << sizeof(a) << endl;
    cout << "############ " << sizeof(b) << endl;

    cout << sizeof(prof) << endl;
    return 0;
}
2024/4/7 18:02
加载中...