C++スコーラ

オーバーライド

最終更新:

cschola

- view
管理者のみ編集可

オーバーライド

オーバーライド

基底クラスの関数は派生クラスで上書きすることが出来ます。
これをオーバーライドと呼び、同じ名前でも派生先によって動作を変えることができます。

/*--------------Person.hの中身----------------*/
#pragma once
#include <iostream>
#include < string >


class Person{
protected:
	std::string name;	// 名前
	int age;	// 年齢

public:
	Person(std::string name, int age);	// コンストラクタ
	virtual ~Person();		// デストラクタ

	void SelfIntroduction()	// 自己紹介
};

/*--------------Person.cppの中身----------------*/
#include "Person.h"
using namespace std;
Person::Person(string name, int age){
	this->name = name;
	this->age = age;
}
Person::~Person(){

}

void Person::SelfIntroduction(){
    cout << name << "、"  << age << "歳です。" << endl;
}

/*--------------Student.hの中身----------------*/
#pragma once
#include "Person.h"

class Student : public Person {
private:
	int id;		// 学籍番号

public:
	Student(std::string name, int age, int id);	// コンストラクタ
	~Student(); 	// デストラクタ

	void SelfIntroduction()	// 自己紹介
	int GetID();	// 学籍番号のゲッター
};

/*--------------Student.cppの中身----------------*/
#include "Student.h"
using namespace std;
Student::Student(string name, int age, int id) : Person(name, age) {
	this->id = id;
}
Student::~Student(){

}

void Student::SelfIntroduction(){
    cout << name << "、"  << age << "歳 学生です。" << endl;
}

int Student::GetID(){
	return id;
}

/*--------------main.cppの中身----------------*/
#include "Student.h"

int main(){
	Person* satou = new Person("佐藤", 69);		// Personクラス
	Student* suzuki = new Student("鈴木", 24, 241035);	// Studentクラス

	satou->SelfIntroduction();	// 自己紹介(Person)
	suzuki->SelfIntroduction();	// 自己紹介(Student)

        delete satou;
        delete suzuki;

	return 0;
}

testcounter
合計 -
今日 -
昨日 -
目安箱バナー