1
0

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-14

コンストラクタ

コンストラクタとは、クラスのオブジェクト作成において初期化を行うための特別な関数のこと
初期値を代入する役割を担う
コンストラクタはクラス名と同じ名前にする

コンストラクタの構文

class クラス名 {
  public:
    1 メンバ変数1
    2 メンバ変数2
    ...
    // メンバ変数1を初期化するコンストラクタ
    クラス名(a 引数a) {
      メンバ変数1 = 引数a
    }
    // 複数のメンバ変数を初期化するコンストラクタ
    クラス名(a 引数a, b 引数b, ...) {
      メンバ変数1 = 引数a
      メンバ変数2 = 引数b
      ...
    }
}

コンストラクタを用いたプログラム

#include <iostream>
using namespace std;
 
class Student {
  public:
    string name;
    int score;

    Student(string str) {
      name = str;
    }
    Student(string str, int x) {
      name = str;
      score = x;
    }
};

int main() {
  Student Taro("Taro");
  cout << Taro.name << endl;
  Student Jiro("Jiro", 100);
  cout << Jiro.name << endl;
  cout << Jiro.score << endl;
}
Taro
Jiro
100

デストラクタ

オブジェクトが破棄されるときに自動的に実行される関数
デストラクタはチルダ記号を使って~クラス名と定義する

デストラクタの用途

  • 動的に確保したメモリの解放
  • ファイルのクローズ処理

デストラクタの構文

~クラス名(){
  // デストラクタの処理
}

デストラクタを用いたプログラム

#include <iostream>
using namespace std;
 
class Student {
  public:
    Student(){
      cout << "コンストラクタの処理" << endl;
    }
    ~Student(){
      cout << "デストラクタの処理" << endl;
    }
};

int main() {
  Student student;
  return 0;
}
コンストラクタの処理
デストラクタの処理

コピーコンストラクタ

オブジェクトをコピーしたときに実行される関数

コピーコンストラクタの構文

クラス名(const クラス名 &引数) {
  // コピーコンストラクタの処理
}

コピーコンストラクタを用いたプログラム

#include <iostream>
using namespace std;
 
class Student {
  public:
    Student(){
      cout << "コンストラクタの処理" << endl;
    }
    Student(const Student &obj){
      cout << "コピーコンストラクタの処理" << endl;
    }
};

int main() {
  Student Taro;
  Student Jiro = Taro;
  return 0;
}
コンストラクタの処理
コピーコンストラクタの処理

次の記事

【C++】基礎を学ぶ⑲~継承~

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?