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");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值