Struct
Quick Notes
Section titled “Quick Notes”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.
Syntax
Section titled “Syntax”struct Point{ int x; int y;};Example
Section titled “Example”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); }};Aggregate Initialization
Section titled “Aggregate Initialization”struct User{ int id; std::string name;};
User user{1, "Ada"};Common Mistakes
Section titled “Common Mistakes”- 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
structvàclass.
Search Keywords
Section titled “Search Keywords”struct cấu trúc constructor method aggregate initialization public