C++の構造体
[複数の] [同じ] 型[のデータ] を格納できますが、[もし、ある生徒の][氏名](文字列)、[年齢]([整数])、[成績]([浮動小数点数])[を格納したい場合は]?
[これには]struct——[複数の異なる]type[の]変数[を1つの単位としてまとめる]ことが必要になります。
1. struct とは何ですか?
(1) 1.1 [生活の中の]struct
| [生活シーン] | 番組[での対応] |
|---|---|
| [名刺1枚]([氏名]、[電話番号]、[メールアドレス]) | struct |
| [1冊の本]([書名]、[著者]、[価格]) | struct |
| [ある学生]([氏名]、[年齢]、[成績]) | struct |
struct[の特徴]:
- membertype[異なる場合あり]
- memory[連続]([array]と同様)
- [「class」の]「前置き」([後ほど学ぶ]class)
(2) 1.2 なぜstructが必要なのか?
[不要]struct([面倒]):
▶ サンプル 2: codeexample (難易度 ⭐)
#include iostream
#include string
int main() {
std::string name1 = "Alice";
int age1 = 20;
double score1 = 92.5;
std::string name2 = "Bob";
int age2 = 21;
double score2 = 88.0;
// ... 3 × 100!
return 0;
}
[用]struct([簡潔]):
#include iostream
#include string
struct Student {
std::string name;
int age;
double score;
};
int main() {
Student s1 = {"Alice", 20, 92.5};
Student s2 = {"Bob", 21, 88.0};
// ...!
return 0;
}
2. struct[の]宣言と[定義]
(1) 2.1 struct の宣言
[文法]:
struct {
1 1;
2 2;
...
};
例:
#include iostream
#include string
// ...
struct Student {
std::string name;
int age;
double score;
}; // ⚠️:!
int main() {
// ...
return 0;
}
💡 [ポイント]: structの宣言は[セミコロン]で[終わらせる]こと![これは初心者がよく犯す]間違いです。
3. struct変数の作成と初期化
(1) 3.1 [作成]structvariable
Student s1; // Student s1
(2) 3.2 struct変数の初期化
[方法1]:[宣言順に初期化]
Student s1 = {"Alice", 20, 92.5};
[方法2]:[指定]member[初期化](C++20、[推奨])
Student s1 = {.name = "Alice", .age = 20, .score = 92.5};
[方法3]:[個別に値を設定]
Student s1;
s1.name = "Alice";
s1.age = 20;
s1.score = 92.5;
💡 [ヒント]: [方法1または方法2の使用をお勧めします]、[より簡潔です]。
4. [アクセス]structmember
(1) 4.1 [読み取り]member
[文法]:
.
例:
#include iostream
#include string
struct Student {
std::string name;
int age;
double score;
};
int main() {
Student s1 = {"Alice", 20, 92.5};
std::cout << ":" << s1.name << std::endl; // Alice
std::cout << ":" << s1.age << std::endl; // 20
std::cout << ":" << s1.score << std::endl; // 92.5
return 0;
}
(2) 4.2 [編集]メンバー
Student s1 = {"Alice", 20, 92.5};
s1.score = 95.0; // ...
std::cout << ":" << s1.score << std::endl; // 95.0
5. struct[引数として渡す場合]
(1) 5.1 [伝]値([推奨されません])
void printStudent(Student s) { // ❌ value:,
std::cout << ":" << s.name << std::endl;
}
(2) 5.2 [伝]参考文献([推奨])
void printStudent(const Student& s) { // ✅ reference:,modify
std::cout << ":" << s.name << std::endl;
std::cout << ":" << s.age << std::endl;
std::cout << ":" << s.score << std::endl;
}
💡 [黄金律]: struct[引数として渡す場合]、[優先して] const 参照を使用する——[コピーによるオーバーヘッドを回避できる]上に、[誤った変更を防ぐ]ことができる。
6. structarray
struct[も]配列を構成できます!
例:[学生]配列 (難易度 ⭐⭐)
#include iostream
#include string
struct Student {
std::string name;
int age;
double score;
};
int main() {
Student students[3] = {
{"Alice", 20, 92.5},
{"Bob", 21, 88.0},
{"Charlie", 19, 95.0}
};
// ...
for (int i = 0; i < 3; i++) {
std::cout << "==========" << i + 1 << " ==========" << std::endl;
std::cout << ":" << students[i].name << std::endl;
std::cout << ":" << students[i].age << std::endl;
std::cout << ":" << students[i].score << std::endl;
std::cout << std::endl;
}
return 0;
}
出力:
========== 1 ==========:Alice:20:92.5
========== 2 ==========:Bob:21:88.0
========== 3 ==========:Charlie:19:95.0
7. 演習:[学生成績管理](struct版)
▶ サンプル 1: [学生の成績管理の全体像] (難易度 ⭐⭐⭐)
#include iostream
#include string
#include vector // vector,
struct Student {
std::string name;
int age;
double score;
};
// ...
void addStudent(Student students, int& count);
void printStudents(const Student students, int count);
double calculateAverage(const Student students, int count);
int main() {
const int MAX_STUDENTS = 100;
Student students[MAX_STUDENTS];
int count = 0;
int choice;
do {
std::cout << "========== ==========" << std::endl;
std::cout << "1." << std::endl;
std::cout << "2." << std::endl;
std::cout << "3. points" << std::endl;
std::cout << "4." << std::endl;
std::cout << "(1-4):";
std::cin >> choice;
if (choice == 1) {
addStudent(students, count);
} else if (choice == 2) {
printStudents(students, count);
} else if (choice == 3) {
if (count == 0) {
std::cout << "!" << std::endl;
} else {
std::cout << "points:" << calculateAverage(students, count) << std::endl;
}
} else if (choice == 4) {
std::cout << "!" << std::endl;
} else {
std::cout << ": 1-4!" << std::endl;
}
std::cout << std::endl;
} while (choice != 4);
return 0;
}
// ...
void addStudent(Student students, int& count) {
if (count >= 100) {
std::cout << "!" << std::endl;
return;
}
std::cout << ":";
std::cin.ignore();
std::getline(std::cin, students[count].name);
std::cout << ":";
std::cin >> students[count].age;
std::cout << ":";
std::cin >> students[count].score;
count++;
std::cout << "!" << std::endl;
}
void printStudents(const Student students, int count) {
if (count == 0) {
std::cout << "!" << std::endl;
return;
}
std::cout << "\n========== ==========" << std::endl;
for (int i = 0; i < count; i++) {
std::cout << i + 1 << ".:" << students[i].name
<< ",:" << students[i].age
<< ",:" << students[i].score << std::endl;
}
std::cout << "================================\n\n";
}
double calculateAverage(const Student students, int count) {
if (count == 0) {
return 0.0;
}
double sum = 0.0;
for (int i = 0; i < count; i++) {
sum += students[i].score;
}
return sum / count;
}
8. [よくある]エラー
(1) 8.1 [セミコロンを書き忘れた]
エラー例:
struct Student { // ❌ write
std::string name;
int age;
} // ❌ Yes
int main() {
// ...
}
コンパイルエラー[詳細]:
error: expected ';' after struct definition
(2) 8.2 [存在しない]メンバーへのアクセス
エラー例:
struct Student {
std::string name;
int age;
};
int main() {
Student s1;
s1.score = 92.5; // ❌:Student Yes score
return 0;
}
❓ よくある質問
struct [のデフォルトのアクセス権限は] public([パブリック]) > - class [のデフォルトのアクセス権限は] private([プライベート])Q:structs basicsについて最も重要なことは何ですか? A:まず核心概念を理解し、その後実践的な例で練習することが重要です。
📖 まとめ
- struct[複数の異なる]型[の]変数[を1つの単位としてまとめる]
- [声明]struct:
struct struct[名] { member[列表] };([注意:セミコロン]!) - [初期化]:
struct[名] variable name = {value1, value2, ...}; - [アクセス]メンバー:
variable name.member[名] - [引数として使用する場合]、[優先的に]
constを参照 - struct[は配列を構成することもできる]
📝 練習問題
-
初心者(難易度 ⭐):
Bookという構造体を定義し、[書名]、[著者]、[価格]の3つのメンバを含める。Bookという変数を2つ作成し、[それらを]出力する。 -
中級(難易度 ⭐⭐): [定義する]
Rectangle構造体で、[幅と高さの2つの]メンバを含む。
- [作成する]関数
double calculateArea(const Rectangle& r)[面積の計算] - [作成する]関数
double calculatePerimeter(const Rectangle& r)[周長の計算] main[でテスト]
- 上級(難易度 ⭐⭐⭐):
[定義する]
Datestruct([年]、[月]、[日])、[作成する]関数[日付が有効かどうかを判定する]([例] 2024-02-29 [有効]、2023-02-29 [無効])。
- struct struct:[異なる]型[のデータを1つの単位にまとめる]
- member[アクセス用] . operator,pointer[用] ->
- [初期化]:[一括初期化] {} [または] member [個別に値を設定]
- struct[として使用可能]function[引数と戻り値]value
- structarray[複数のレコードの管理]
9. 🚀 次は
[struct]を学んだので、[次は] フェーズ4(ポインタ[と]参照)に進みます――[これは] C++ [の最も核心的で、かつ最も難しい部分]ですが、[習得すれば、より効率的な]コードが書けるようになります!



