【问题标题】:Why is the sizeof() returning 4 for this class with 2 bytes为什么 sizeof() 为这个有 2 个字节的类返回 4
【发布时间】:2018-06-23 19:43:16
【问题描述】:

当我打印下面定义的类的 sizeof(SenseNode) 时,返回 4。由于有 2 个 uint8_t 私有成员,我原以为它是 2 个。 其他 2 个字节我用的是什么?

enum NodeType { unknown = 255, temperature=0, button=1, text=2, page=3, dualstate=4, slider=5, alarmHandler=6, clock=7, gps=8,
                         yawpitchroll = 9, gsm = 10, alert = 11 };

class SenseNode {
  public:
    SenseNode(uint8_t id) : SenseNode(id, NodeType::unknown) {};
    SenseNode(uint8_t id, NodeType type) : id(id), nodeType(type) {};
    virtual ~SenseNode() = default;

    // Dispatcher of notifyObserver
    virtual void notifyObserver2(SenseObserver* observer);

    /* Accessor for property Id */
    uint8_t getId() { return id; }
    NodeType getNodeType() { return nodeType; }
  private:
    uint8_t id = 0;
    uint8_t nodeType = NodeType::unknown;
};

【问题讨论】:

  • Size of C++ classes的可能重复
  • 虚拟指针,记住!!!顺便说一句,很难想象通过某些协议传输整个虚拟对象
  • 我希望它至少是 8。
  • 你平台上的sizeof(void*)是什么?
  • @HolyBlackCat 他在 arduino 所以 2

标签: c++ arduino-esp8266


【解决方案1】:

首先,SenseNode 类是多态的,因为你有一个虚函数。编译器添加指向 vtable 的指针,因此类的大小取决于平台。在你的例子中,指针的大小是 2,我们有 2 + 1 + 1 = 4。你可以阅读这个主题 herehere

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    相关资源
    最近更新 更多