[英]Access struct elements in a class linitalizer list
I'm working on an embedded-system project using EFM32GG11 series micro-controller.我正在使用 EFM32GG11 系列微控制器进行嵌入式系统项目。 In project I've to read data from multiple serial port, process the data and forward the data to server via Ethernet.
在项目中,我必须从多个串口读取数据,处理数据并通过以太网将数据转发到服务器。
I've created a class that will handle serial port.我创建了一个 class 来处理串口。 Multiple object of this class will be created.
将创建此 class 的多个 object。
I've created a constructor with initialize list.我创建了一个带有初始化列表的构造函数。 I've a question: Is their a way to directly access structure member in initialization list?
我有一个问题:他们是一种直接访问初始化列表中结构成员的方法吗? - uart_init.baudRate(baud_rate)
- uart_init.baudRate(baud_rate)
class SerialPort {
public :
enum PortList{
COM1, //RS-232
COM2 //RS-232 -- 8 more ports
};
private:
PortList port_no;
UARTDRV_Init_t uart_init;
uint32_t baud_rate;
char parity;
uint8_t stop_bit;
bool single_line_mode;
uint16_t block_time; //in milli-seconds
public:
SerialPort(PortList port_no, uint16_t baud_rate, char parity, uint8_t stop_bit,
bool single_line_mode, uint16_t block_time) : port_no(port_no), uart_init.baudRate(baud_rate), parity(parity), stop_bit(stop_bit), single_line_mode(single_line_mode),
block_time(block_time)
{
//Further processing post initialization
}
};
UARTDRV_Init_t Strurcture: UARTDRV_Init_t 结构:
typedef struct {
USART_TypeDef *port; ///< The peripheral used for UART
uint32_t baudRate; ///< UART baud rate
} UARTDRV_InitUart_t;
You can use designated initializers (since C++20) to specify the member to be initialized.您可以使用指定的初始化器(C++20 起)来指定要初始化的成员。 Eg
例如
SerialPort(PortList port_no, uint16_t baud_rate, char parity, uint8_t stop_bit,
bool single_line_mode, uint16_t block_time) : port_no(port_no), uart_init {.baudRate=baud_rate}, parity(parity), stop_bit(stop_bit), single_line_mode(single_line_mode),
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
block_time(block_time)
{
//Further processing post initialization
}
Before C++17, we can only initialize the data member itself in member initializer list and can't specify its subobject further more.在 C++17 之前,我们只能在成员初始化器列表中初始化数据成员本身,不能进一步指定其子对象。
If you know the what the default for port should be, you could do it this way, assuming port is initialized to nullptr
or something:如果你知道端口的默认值应该是什么,你可以这样做,假设端口被初始化为
nullptr
或其他东西:
SerialPort(PortList port_no, uint16_t baud_rate, char parity, uint8_t stop_bit,
bool single_line_mode, uint16_t block_time) : port_no(port_no), uart_init {nullptr, baud_rate}, parity(parity), stop_bit(stop_bit), single_line_mode(single_line_mode),
block_time(block_time)
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.