Skip to content

Struct

struct giống class nhưng member mặc định là public. Thường dùng cho data object nhỏ hoặc record. Struct vẫn có constructor, method, static member và operator overload.

struct Point
{
int x;
int y;
};
struct Point
{
int x = 0;
int y = 0;
Point(int xValue, int yValue) : x(xValue), y(yValue) {}
int manhattan() const
{
return std::abs(x) + std::abs(y);
}
};
struct User
{
int id;
std::string name;
};
User user{1, "Ada"};
  • Quên dấu ; sau định nghĩa struct.
  • Đưa invariant phức tạp vào struct public mà không kiểm soát.
  • Nhầm default access của struct và class.

struct cấu trúc constructor method aggregate initialization public