1. 程式人生 > >Essential c++ 5.2節 面向物件程式設計初識

Essential c++ 5.2節 面向物件程式設計初識

知識點: 1.為了讓member function 在運動時動態進行,需要在它宣告前加關鍵字virtual(虛擬函式) 2. 基類的解構函式前加virtual是因為 在實現多型時,當用基類操作派生類,在析構時防止只析構基類而不析構派生類的狀況發生。 3. 編譯器中沒有顯示解構函式的列印內容是因為解構函式是在main函式結束後進行的,當用pause暫停時,解構函式還沒執行。 4. 派生類可直接用基類的資料成員,在初始化值時,直接呼叫Book(title, author)即可,對應_title(title) , _author(author) 5. 關鍵字protected,被宣告為protected的所有成員都可以被派生類直接訪問。

#include<iostream>
#include<string>
using namespace std;

class LibMat{
public:
	LibMat(){ cout << "LibMat::LibMat() default constructor!\n"; }
	//動態繫結,用虛擬函式,在函式申明前加關鍵字virtual
	virtual ~LibMat(){ cout << "LibMat::~LibMat() destructor!\n"; }
	virtual void print() const
	{
		cout <<
"LibMat::print() --I am a LibMat object!\n"; } }; //現在我們定義一個非成員函式print(),它接受一個引數,其形式為const LibMat reference void print(const LibMat &mat) { cout << "in global print(): about to print mat.print()\n"; mat.print(); } //實現派生類Book class Book :public LibMat{ public: Book(const string &title,
const string &author) :_title(title), _author(author) { cout << "Book::Book( " << _title << ", " << _author <<") constructor\n"; } virtual ~Book(){ cout << "Book::~Book() destructor!\n"; } virtual void print()const { cout << "Book::print()--I am a Book object!\n" << "My title is: " << _title << '\n' << "My author is: " << _author << endl; } // title()和author()是兩個訪問函式,都是non-virtual inline 函式 const string &title() const { return _title; } const string &author() const { return _author; } protected: //被宣告為protected的所有成員都可以被派生類直接訪問 string _title; string _author; }; //實現Book的派生類 class AudioBook :public Book { public: AudioBook(const string &title, const string &author, const string &narrator) :Book(title, author), _narrator(narrator) { cout<<"AudioBook::AudioBook( "<<_title << ", " << _author << ", " << _narrator << ") constructor\n"; } ~AudioBook() { cout << "AudioBook::~AudioBook() destructor!\n"; } virtual void print()const { cout << "AudioBook::print()--I am an AudioBook object!\n" << "My title is: " << _title << '\n' << "My author is: " << _author << '\n' << "My narrator is: " << _narrator << endl; } const string &narrator() const { return _narrator; } protected: string _narrator; }; int main() { cout << 1 << endl; LibMat libmat; print(libmat); cout << 2 << endl; Book b("The Castle", "Franz Kafka"); print(b); cout << 3 << endl; AudioBook ab("Man Without Qualities", "Robert Musil", "Kenneth Meter"); print(ab); system("pause"); }