在C++中,可以使用结构体(struct)来表示一个自定义的数据类型。要正确地初始化结构体,可以使用以下几种方法:
- 使用初始化列表:
struct Person { std::string name; int age; }; Person p = {"Alice", 25};
- 使用默认构造函数:
struct Point { int x; int y; Point() : x(0), y(0) {} }; Point p;
- 使用成员初始化列表:
struct Rectangle {
int width;
int height;
Rectangle(int w, int h) : width(w), height(h) {}
};
Rectangle r(10, 20);
- 使用聚合初始化:
struct Vector { double x; double y; }; Vector v = {1.0, 2.0};
无论使用哪种方法,都可以正确地初始化结构体。选择使用哪种方法取决于具体的情况和个人偏好。