クラス間の継承を実装する
このステップでは、C++ における継承について学びます。オブジェクト指向プログラミングの基本概念であり、既存のクラスを基に新しいクラスを作成することができます。
WebIDE で student.cpp
ファイルを開き、継承を示すようにコードを変更します。
#include <iostream>
#include <string>
// 基底クラス
class Person {
protected:
std::string name;
int age;
public:
// コンストラクタ
Person(std::string personName, int personAge) {
name = personName;
age = personAge;
}
// 基本情報を表示するメソッド
void displayInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
}
};
// 派生クラス:Student は Person から継承する
class Student : public Person {
private:
double gpa;
std::string major;
public:
// 基底クラスのコンストラクタを呼び出すコンストラクタ
Student(std::string studentName, int studentAge, double studentGPA, std::string studentMajor)
: Person(studentName, studentAge) {
gpa = studentGPA;
major = studentMajor;
}
// Student に固有の追加メソッド
void displayStudentInfo() {
// 基底クラスのメソッドを呼び出す
displayInfo();
std::cout << "GPA: " << gpa << std::endl;
std::cout << "Major: " << major << std::endl;
}
};
// もう一つの派生クラス:Employee は Person から継承する
class Employee : public Person {
private:
std::string company;
double salary;
public:
// 基底クラスのコンストラクタを呼び出すコンストラクタ
Employee(std::string employeeName, int employeeAge, std::string employeeCompany, double employeeSalary)
: Person(employeeName, employeeAge) {
company = employeeCompany;
salary = employeeSalary;
}
// Employee に固有の追加メソッド
void displayEmployeeInfo() {
// 基底クラスのメソッドを呼び出す
displayInfo();
std::cout << "Company: " << company << std::endl;
std::cout << "Salary: $" << salary << std::endl;
}
};
int main() {
// 派生クラスのオブジェクトを作成する
Student student("Alice Johnson", 20, 3.75, "Computer Science");
std::cout << "Student Information:" << std::endl;
student.displayStudentInfo();
std::cout << "\n";
Employee employee("Bob Smith", 35, "Tech Corp", 75000.0);
std::cout << "Employee Information:" << std::endl;
employee.displayEmployeeInfo();
return 0;
}
プログラムをコンパイルして実行します。
g++ student.cpp -o student
./student
例の出力:
Student Information:
Name: Alice Johnson
Age: 20
GPA: 3.75
Major: Computer Science
Employee Information:
Name: Bob Smith
Age: 35
Company: Tech Corp
Salary: $75000
継承に関する要点:
- 基底クラス (Person) には共通の属性が含まれる
- 派生クラス (Student、Employee) は基底クラスから継承する
: public BaseClassName
を使用して継承する
- 派生クラスで新しい属性やメソッドを追加できる
- 派生クラスで基底クラスのメソッドを使用できる