知识点:
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");
}