#include <iostream>
#include <string>
#include <string_view>
#include <utility>
#include <memory>
#include <vector>
// 列挙型による厳密な型安全の確保
enum class Gender {
Male,
Female,
Other
};
// ユーティリティ: 性別を文字列に変換
constexpr std::string_view to_string(Gender gender) noexcept {
switch (gender) {
case Gender::Male: return "男";
case Gender::Female: return "女";
case Gender::Other: return "その他";
}
return "不明";
}
// インターフェースの定義 (拡張性を考慮)
class ISpeaker {
public:
virtual ~ISpeaker() = default;
virtual void say() const = 0;
};
// クラス名の修正とインターフェースの継承
class Human : public ISpeaker {
private:
std::string name_;
std::string job_;
int age_{0};
Gender gender_{Gender::Other};
public:
// デフォルトコンストラクタの禁止 (不完全なオブジェクトを作らせない)
Human() = delete;
// std::moveによるコピーコストの削減 (高速化)
explicit Human(std::string name, std::string job, int age, Gender gender) noexcept
: name_(std::move(name)), job_(std::move(job)), age_(age), gender_(gender) {}
// 読み取り専用(const)メソッド、noexceptによる例外安全性
void say() const noexcept override {
std::cout << "你好!我是" << name_ << "。\n"
<< "我的性别是" << to_string(gender_) << "。\n"
<< "我的年龄是" << age_ << "岁。\n"
<< "我的职业是" << job_ << "。\n" << std::endl;
}
// ゲッターの追加 (カプセル化の維持)
[[nodiscard]] std::string_view getName() const noexcept { return name_; }
};
int main() {
// 現代的なC++の標準出力
std::cout << "--- 現代的C++プログラム 開始 ---\n" << std::endl;
// スマートポインタ(std::unique_ptr)による安全なメモリ管理
// メモリリークを100%防止
std::vector<std::unique_ptr<ISpeaker>> community;
// データの追加
community.push_back(std::make_unique<Human>("大須賀晴久", "下ネタリスト", 13, Gender::Male));
community.push_back(std::make_unique<Human>("サンプル太郎", "エンジニア", 30, Gender::Male));
// ポリモーフィズム(多態性)を利用した一括実行
for (const auto& member : community) {
member->say();
}
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: