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

カプセル化

知らなくても良いクラスオブジェクト内部の仕組みを隠すこと

なぜカプセル化するか

データの変更をオブジェクト自身に任せることによって、バグを引き起こさせないようにする
不正なデータ変更禁止する条件を設定することができる

カプセル化を用いたプログラム

privateを使用する

#include <iostream>
using namespace std;
 
class Test {
  private:
    int num;
  public:
    void setNum(int x);
};

void Test::setNum(int x) {
  num = x;
  // cout << test.num << endl; ビルドエラーになる
  cout << num << endl;
}

int main() {
  Test test;
  test.setNum(10);
}
10

getter/setter

getter/setterとは、メンバ変数に値を取得/設定するためだけを目的とするメンバ関数のこと

プログラム

#include <iostream>
using namespace std;
 
class Student {
  private:
    int score;
  public:
    void setScore(int x);
    int getScore();
};

void Student::setScore(int x) {
  score = x;
}

int Student::getScore() {
  return score;
}

int main() {
  Student Taro;
  Taro.setScore(90);
  cout << Taro.getScore() << endl;
}
90

不正な値の代入を防ぐ

setterに不正な値の代入を防ぐようなプログラムを書くことで、バグが起きにくいコードになります

負の値が設定されるのを防ぐsetter

void Student::setScore(int x) {
  if (0 > x) {
    x = 0;
  }
  score = x;
}

次の記事

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