【C++】构造函数参数初始化的顺序

下面列出总结:

1.成员变量在使用初始化列表初始化时,与构造函数中初始化成员列表的顺序无关,只与定义成员变量的顺序有关。就是(通常是private下)定义变量的先后顺序。所以一般构造函数的初始化列表和定义顺序相同。

2.如果不使用初始化列表初始化,在构造函数内初始化时,无所谓了,就根据你的逻辑写就行

3.类中const成员常量必须在构造函数初始化列表中初始化。

4.类中static成员变量,只能在类内声明,然后类外初始化。

下面是C++类成员变量初始化顺序:

1) 基类的静态变量或全局变量
2) 派生类的静态变量或全局变量
3) 基类的成员变量
4) 派生类的成员变量

例如:

未调整变量位置时

class H4Protocol : public HciProtocol {
 public:
  H4Protocol(int fd, PacketReadCallback event_cb, PacketReadCallback acl_cb,
             PacketReadCallback sco_cb, PacketReadCallback iso_cb)
      : uart_fd_(fd),
        event_cb_(event_cb),
        acl_cb_(acl_cb),
        sco_cb_(sco_cb),
        iso_cb_(iso_cb),
        hci_packetizer_([this]() { OnPacketReady(); }) {}

  size_t Send(uint8_t type, const uint8_t* data, size_t length);

  void OnPacketReady();

  void OnDataReady(int fd);

  HciPacketType hci_packet_type_{HCI_PACKET_TYPE_UNKNOWN};
  hci::HciPacketizer hci_packetizer_;
  
 private:
  int uart_fd_;

  PacketReadCallback event_cb_;
  PacketReadCallback acl_cb_;
  PacketReadCallback sco_cb_;
  PacketReadCallback iso_cb_;

  
};

报错

In file included from hardware/interfaces/bluetooth/1.0/default/h4_protocol.cc:17:
hardware/interfaces/bluetooth/1.0/default/h4_protocol.h:39:9: error: field 'iso_cb_' will be initialized after field 'hci_packetizer_' [-Werror,-Wreorder-ctor]
        iso_cb_(iso_cb),

修改后

class H4Protocol : public HciProtocol {
 public:
  H4Protocol(int fd, PacketReadCallback event_cb, PacketReadCallback acl_cb,
             PacketReadCallback sco_cb, PacketReadCallback iso_cb)
      : uart_fd_(fd),
        event_cb_(event_cb),
        acl_cb_(acl_cb),
        sco_cb_(sco_cb),
        iso_cb_(iso_cb),
        hci_packetizer_([this]() { OnPacketReady(); }) {}

  size_t Send(uint8_t type, const uint8_t* data, size_t length);

  void OnPacketReady();

  void OnDataReady(int fd);

 private:
  int uart_fd_;

  PacketReadCallback event_cb_;
  PacketReadCallback acl_cb_;
  PacketReadCallback sco_cb_;
  PacketReadCallback iso_cb_;
 public:
  HciPacketType hci_packet_type_{HCI_PACKET_TYPE_UNKNOWN};
  hci::HciPacketizer hci_packetizer_;
  
};

你可能感兴趣的:(test,c++,java,开发语言)