选择java 进入自由开放的国度

随笔 - 49, 文章 - 3, 评论 - 154, 引用 - 1
数据加载中……

C++中关于继承的多态

LibMat
Book
AudioBook

Class:LibMat
class LibMat  
{
public:
    LibMat();
    virtual 
~LibMat();
    virtual 
void print() const;
}
;
// LibMat.cpp: implementation of the LibMat class.
//
//////////////////////////////////////////////////////////////////////

#include 
"LibMat.h"
#include 
<iostream>

using namespace std;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

LibMat::LibMat()
{
 cout 
<< "LibMat::LibMat() constructor\n";
}


LibMat::
~LibMat()
{
  cout 
<< "LibMat :: ~ LibMat() destructor\n";
}


void LibMat ::print() const 
{
  cout 
<< "LibMat::print() -- I am a LibMat object!\n";
}

Class:Book
#include "LibMat.h"
#include 
<string>
using namespace std;

class Book : public LibMat  
{
public:
    Book(
const string &const string &);
    virtual 
~Book();
    virtual 
void print() const;
    
const string& title()  const{return _title;};
    
const string& author() const{return _author;};
protected:
    string _title;
    string _author;
}
;
#include "Book.h"
#include 
<iostream>
using namespace std;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

Book::Book(
const string &title, const string &author)
: _title(title), _author(author)
{
  cout 
<< "Book::Book(" << _title << "" << _author << ") constructor\n";
}


Book::
~Book()
{
 cout 
<< "Book:~Book destructor!\n";
}


void Book::print() const 
{
  cout 
<< "Book ::print() -- I am a Book object!\n"
       
<< "My Title is : " << _title << ", My author is : " << _author << endl;
}
测试代码:main.cpp
#include "AudioBook.h"
#include 
<iostream>
using namespace std;


void print(const LibMat&);

void main ()
{
  
//LibMat libmat;
  
//print(libmat);
  
  
//polymorphism
  
//Book b("The Castle", "Franz Kafka");
  
//print(b);

  cout 
<<"----------------------\n";
  AudioBook a(
"The Castle""Franz kafka""Hanhongbo");
  print(a);
}


void print(const LibMat& mat)
{
  cout 
<< "in global print():\n";

  mat.print();
}

posted on 2006-01-08 20:37 soochow_hhb 以java论成败 以架构论英雄 阅读(338) 评论(0)  编辑  收藏 所属分类: Reading


只有注册用户登录后才能发表评论。


网站导航: