國立屏東大學 資訊工程學系 物件導向程式設計
Book類別是用以對「真實世界(real world)」中的「書籍」進行「抽象對映(mapping abstraction)」的定義。
class Book { private: string title; string author; string ISBN; public: void setTitle(string t) {title=t;} void setAuthor(string a) {author=a;} void setISBN(string i) {ISBN=i;} string getTitle() {return title;} string getAuthor() {return author;} string getISBN() {return ISBN;} Book() { title="unknown"; author="unknown"; ISBN="undefined"; } Book(string t, string a, string isbn) { title=t; author=a; ISBN=isbn; } ~Book() { cout << author << "'s book has been deleted!" << endl; } void showInfo() { cout << title << " (" << author << ")" << ", ISBN:" << ISBN << endl; } };
Book b1,b2; b1.setTitle("Programming in C"); b1.setAuthor("Jun Wu"); b1.setISBN("987-123-456-1"); b2=b1; b2.setTitle("Smart Programming"); b2.setISBN("987-111-222-3"); cout << b1.getTitle() << "(" << b1.getAuthor() << "), " << b1.getISBN() << endl; cout << b2.getTitle() << "(" << b2.getAuthor() << "), " << b2.getISBN() << endl;