CのstructとC++のclass
C structはデータをまとめ、C++ classはprivate stateとmethodでinvariantを守ります。
CのstructとC++のclassとは?
C structはデータをまとめ、C++ classはprivate stateとmethodでinvariantを守ります。
関連するstateとbehaviorをモデル化します。
重要なポイント
- 操作より先にinvariantを定義します。
- 空・満杯・allocation失敗を処理します。
- 計算量とownershipを一緒に評価します。
CとC++のコード例
C
main.c
#include <stdio.h>
typedef struct {
const char *owner;
double balance;
} Account;
void deposit(Account *account, double amount) {
if (amount > 0) {
account->balance += amount;
}
}
int main(void) {
Account account = {"Ada", 100.0};
deposit(&account, 25.0);
printf("%s: %.2f\n", account.owner, account.balance);
return 0;
}
Ada: 125.00
C++
main.cpp
#include <iomanip>
#include <iostream>
#include <string>
#include <utility>
class Account {
std::string owner_;
double balance_;
public:
Account(std::string owner, double balance)
: owner_(std::move(owner)), balance_(balance) {}
void deposit(double amount) {
if (amount > 0) {
balance_ += amount;
}
}
void print() const {
std::cout << owner_ << ": " << std::fixed
<< std::setprecision(2) << balance_ << '\n';
}
};
int main() {
Account account("Ada", 100.0);
account.deposit(25.0);
account.print();
}
Ada: 125.00
CとC++の比較
Cはstruct pointerを関数へ渡します。C++ classはbalanceをprivateにして有効なmethodだけで変更します。
C
構造体と操作は分離され、allocationは明示的です。
C++
classとcontainerがinvariantとresourceを管理します。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- 空と容量境界をテストします。
- cleanupを実装しleakを確認します。
- standard containerと比較します。