Menu
Coddy logo textTech

属性(データメンバー)

CoddyのC++ジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 9/104。

データメンバー(属性)は、オブジェクトの状態を格納します。通常は private として宣言され、public な getter/setter メソッドを通じてアクセスされます。これをカプセル化と呼びます。

private データメンバー

class BankAccount {
private:
    std::string accountName;
    int balance;
};

publicゲッターとセッター

class BankAccount {
private:
    std::string accountName;
    int balance;

public:
    void setBalance(int balance) {
        this->balance = balance;
    }
    
    int getBalance() {
        return this->balance;
    }
};

検証付きのセッター

void BankAccount::setBalance(int balance) {
    if (balance >= 0) {
        this->balance = balance;
    }
}

アクセス指定子

class MyClass {
private:    // クラス内でのみアクセス可能
    int secret;

public:     // どこからでもアクセス可能
    int getSecret() { return secret; }

protected:  // クラスおよびサブクラスでアクセス可能
    int shared;
};

データメンバーをprivateにすると、外部のコードから隠されます。ゲッターはその値を返し、セッターは必要に応じて検証を行いながら値を変更します。これによりデータが保護され、アクセス方法を制御できます。

challenge icon

チャレンジ

中級

BankAccount クラスを作成し、private データメンバーと public アクセスメソッドを定義してください:

  • private メンバー:accountName(string)、balance(int)
  • セッター:setAccountNamesetBalance
  • ゲッター:getAccountNamegetBalance
  • deposit(int amount):amount > 0 の場合、balance に加算する
  • withdraw(int amount):可能な場合は "Success" を返し、それ以外の場合は "Insufficient funds" を返す

自分で試してみよう

#include <iostream>
#include "BankAccount.h"

int main() {
    std::string name;
    int initial, depositAmt;
    std::getline(std::cin, name);
    std::cin >> initial >> depositAmt;
    
    BankAccount account;
    account.setAccountName(name);
    account.setBalance(initial);
    
    std::cout << "Account: " << account.getAccountName() << std::endl;
    std::cout << "Balance: " << account.getBalance() << std::endl;
    
    account.deposit(depositAmt);
    std::cout << "After deposit: " << account.getBalance() << std::endl;
    
    std::string result = account.withdraw(2000);
    std::cout << "Withdraw 2000: " << result << std::endl;
    std::cout << "Final Balance: " << account.getBalance() << std::endl;
    return 0;
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ