目錄表

國立屏東大學 資訊工程學系 物件導向程式設計

Person類別範例9

類別繼承


簡介

Person類別是用以對「真實世界(real world)」中的「人」進行「抽象對映(mapping abstraction)」的定義。

Data Members

Member Functions

Constructor and Destructor

Student類別範例


簡介

Student是繼承自Person類別的類別,用以對「真實世界(real world)」中的「學生」進行「抽象對映(mapping abstraction)」的定義。但比起Person類別,Student類別又更為特別一些,它還多了一個名為ID的data member及相關的setter與getter:

Data Members

Member Functions

Constructor and Destructor

None

Source Code

#include <iostream>
using namespace std;

#ifndef _PERSON_
#define _PERSON_

class Person
{
private:
  string firstname;
  string lastname;

public:  
  Person();
  Person(string, string);
  ~Person();
  void showInfo();
  
  void set_firstname(string fn);
  string get_firstname();
  
  void set_lastname(string ln);
  string get_lastname();  
};
#endif

#include "person.h"

Person::~Person()
{
  cout << "A Person is removed." << endl;
}

Person::Person()
{
  cout << "A Person is created." << endl;
}

Person::Person(string fn, string ln)
{
  firstname=fn;
  lastname=ln;
}

void Person::showInfo()
{
  cout << "Name: " << firstname << " " << lastname << endl;
}

void Person::set_firstname(string fn)
{
  firstname=fn;
}

void Person::set_lastname(string ln)
{
  lastname=ln;
}

string Person::get_firstname()
{
  return firstname;
}

string Person::get_lastname()
{
  return lastname;
}

#ifndef _STUDENT_
#define _STUDENT_
#include "person.h"

class Student : public Person
{
private:
  string ID;
  
public:
  Student();
  Student(string fn, string ln, string id);
  ~Student();
  
  void set_ID(string id);
  
  void set_name(string fn, string ln);
  void set_name(string n);

  string get_ID();
  void showInfo();
};
#endif

#include "student.h"
#include <cctype>

Student::Student()
{
  cout << "A Student is created." << endl;
}

/*
Student::Student(string fn, string ln, string id):Person(fn, ln)
{
  ID=id;
}
*/

Student::Student(string fn, string ln, string id):Person(fn, ln), ID(id)
{
//  ID=id;
}

Student::~Student()
{
  cout << "A Student is removed." << endl;
}

void Student::set_name(string fn, string ln)
{
  set_firstname(fn);
  set_lastname(ln);
}

void Student::set_name(string n)
{
  unsigned pos=n.find(" ");
  set_firstname( n.substr(0,pos));
  set_lastname( n.substr( pos+1, n.size()-(get_firstname()).size()));
}

void Student::set_ID(string id)
{
  ID=id;
}

string Student::get_ID()
{
  return ID;
}

void Student::showInfo()
{
  cout << "Name: " << get_firstname() << " " << get_lastname() << endl;
  cout << "ID: " << ID << endl;  
}

#include <iostream>
using namespace std;

#include "student.h"

int main()
{
  Student amy,tony;
  
  amy.set_name("Amy Chang");
  tony.set_name("Tony", "Wang");
  amy.set_ID("s111418088");
  tony.set_ID("s111418099");
  amy.showInfo();
  tony.showInfo();
  
  return 0;
}

all: person.o student.o
	g++ main.cpp person.o student.o -o main

person.o: person.cpp person.h
	g++ -c person.cpp
	
student.o: student.cpp student.h
	g++ -c student.cpp

clean:
	rm -f *.o main *.*~ *~