#include <iostream>
#include <string>
#include <vector>
#include <memory> // スマートポインタを使うために必要ニダ!

using namespace std;

class Human {
protected:
    string name;
    int age;
    char gender;

public:
    Human(string name, int age, char gender) 
        : name(name), age(age), gender(gender) {}

    virtual ~Human() {
        cout << "Humanのデストラクタが呼ばれたニダ" << endl;
    }

    virtual void sayHello() {
        cout << "こんにちは、" << name << "です。" << endl;
    }
};

class Student : public Human {
private:
    int number;

public:
    Student(string name, int age, char gender, int number) 
        : Human(name, age, gender), number(number) {}

    ~Student() {
        cout << "Studentのデストラクタが呼ばれたニダ" << endl;
    }

    void sayHello() override {
        cout << "学生の" << name << "ニダ!番号は" << number << "ニダ!" << endl;
    }
};

int main() {
    // 1. make_unique を使って作成するニダ!
    // unique_ptr は「所有者が自分だけ」という賢いポインタニダ
    auto person1 = make_unique<Human>("佐藤", 40, 'W');
    auto person2 = make_unique<Student>("田中", 20, 'M', 1);

    // 2. 使い方は普通のポインタと同じ「->」ニダ
    person1->sayHello();
    person2->sayHello();

    // 3. vectorに入れて一括管理もできるニダ
    // unique_ptrを移動(move)させてリストに入れるニダ
    vector<unique_ptr<Human>> people;
    people.push_back(move(person1));
    people.push_back(move(person2));

    cout << "\n--- リストで一括管理ニダ ---" << endl;
    for (const auto& p : people) {
        p->sayHello();
    }

    // 4. deleteを書かなくても、ここで自動的にメモリが解放されるニダ!
    cout << "\n--- プログラム終了(自動でお掃除) ---" << endl;
    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: