3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ⑮~構造体~

Last updated at Posted at 2022-07-11

構造体

構造体とは、新しいデータ型を作るための仕組み
複数の型をまとめた新しい型を定義することができる

構造体の構文

構造体の定義

structを使う

struct 構造体名 {
  1 メンバ変数名1
  2 メンバ変数名2
  3 メンバ変数名3
  ...(必要な分だけ書く)
};

構造体の宣言

構造体名 オブジェクト名;

メンバ変数へのアクセス

オブジェクト.メンバ変数;

構造体の宣言と初期化を同時に行う

構造体名 オブジェクト名 = {メンバ変数1の値, メンバ変数2の値, メンバ変数3の値, ...(必要な分だけ書く)};

構造体を用いたプログラム

#include <iostream>
using namespace std;
 
struct MyPair {
  int x;
  string y;
};
 
int main() {
  MyPair p = {12345, "hello"};
  cout << p.x << endl;
  cout << p.y << endl;
}
12345
hello

メンバ関数

メンバ関数とは、構造体でメンバ変数に対して処理を行う関数のこと

メンバ関数の定義

struct 構造体名 {
  返り値の型 メンバ関数名(引数の型1 引数名1, 引数の型2 引数名2, ...) {
    // 関数の内容
    //   (ここではメンバ変数に直接アクセスすることができる)
  }
};

メンバ関数の呼び出し

オブジェクト.メンバ関数(引数1, 引数2, ...)

メンバ関数を用いたプログラム

#include <iostream>
using namespace std;
 
struct MyPair {
  int x;
  string y;
  // メンバ関数
  void print() {
    cout << x << endl;
    cout << y << endl;
  }
};
 
int main() {
  MyPair p = { 12345, "Hello" };
  p.print();
 
  MyPair q = { 67890, "World" };
  q.print();
}
12345
Hello
67890
World

次の記事

【C++】基礎を学ぶ⑯~クラス~

3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?