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

継承

既存のクラスを引き継いで新しいクラスを作るための仕組み
引き継ぎクラスを基底クラス、引き継いで新しく定義したクラスを派生クラスという

継承の構文

class 基底クラス{
  1 メンバ変数1;
  2 メンバ変数2;
  ...
  a メンバ関数a
  ...
}

class 派生クラス : アクセス指定子 基底クラス{
  3 メンバ変数3;
  ...
  b メンバ関数b;
  ...
}

継承を用いたプログラム

#include <iostream>
using namespace std;
 
class Human {
  public:
    string name;
    void show(){
      cout << name << endl;
    }
};

class Student : public Human {
  public:
    void derived(){
      cout << "Studentは派生クラスです" << endl;
    }
};

int main() {
  Student Taro;
  Taro.name = "taro";
  Taro.show();
  Taro.derived();
  return 0;
}
taro
Studentは派生クラスです

アクセス指定子protected

基本・派生クラス内でのみアクセスできる

protectedを用いたプログラム

#include <iostream>
using namespace std;
 
class Human {
  protected:
    string name;
  public:
    void show(){
      cout << name << endl;
    }
};

class Student : public Human {
  public:
    void setName(string str){
      name = str;
    }
};

int main() {
  Student Taro;
  // Taro.name = "taro"; ビルドエラーが発生する
  Taro.setName("taro");
  Taro.show();
  return 0;
}
taro

コンストラクタが呼ばれる順番

基底クラスから順にコンストラクタが呼ばれる

サンプルプログラム

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

class Student : public Human {
  public:
    Student(){
      cout << "Studentクラスのコンストラクタ" << endl;
    }
};

int main() {
  Student taro;
  return 0;
}
Humanクラスのコンストラクタ
Studentクラスのコンストラクタ

次の記事

【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?