本文意在整理 C++ struct 的用法,和需要注意的地方。
见下面的示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #include <iostream> #include <string> using namespace std; struct Student { string name; int age; double finalExamScore; }; void printStudent(Student& stu) { cout << stu.name << endl; cout << stu.age << endl; cout << stu.finalExamScore << endl; cout << endl; } int main() { Student stu = { "Zhang San", 16, 91.5 }; printStudent(stu); Student* stu2 = new Student(); stu2->name = "Li Si"; stu2->age = 17; stu2->finalExamScore = 92.5; printStudent(*stu2); }
|
输出结果:
1 2 3 4 5 6 7
| Zhang San 16 91.5 Li Si 17 92.5
|
带构造的 struct:
1 2 3 4 5 6
| struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} };
|