⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 inheritdemo.cpp

📁 C++&datastructure书籍源码,以前外教提供现在与大家共享
💻 CPP
字号:
#include <iostream>
#include <string>
using namespace std;

#include "dice.h"

class Person      // abstract base class for every Person
{
  public:
    virtual ~Person() {} 
    
    virtual void ThinkAloud() = 0;     // makes class abstract
    
    virtual void   Reflect()  const
    {   cout << "...As I see it, ...";
    }  
    virtual string Name()  const
    {   return "Ethan";
    }
};

class Simpleton : public Person        // a simple thinker
{
  public:
    Simpleton(const string& name);
    virtual void ThinkAloud();
    
    virtual void   Reflect() const;
    virtual string Name()    const;
    
  private:
    string myName;
};

class Thinker : public Person          // a cogent person
{
  public:
    Thinker(const string& name);
    virtual void ThinkAloud();
    
    virtual void   Reflect() const;
    virtual string Name()    const;
    
  private:
    string myName;
    int    myThoughtCount;
};

Simpleton::Simpleton(const string& name)
  : myName(name)
// postcondition: ready to think    
{  }

void Simpleton::ThinkAloud()
// postcondition: has thought
{   
    cout << "I don't think a lot" << endl;
}

void Simpleton::Reflect() const
// postcondition: has reflected
{   
    Person::Reflect();
    cout << "I'm happy" << endl;
}

string Simpleton::Name() const
// postcondition: returns name    
{   
    return myName + ", a simpleton";
}

Thinker::Thinker(const string& name)
  : myName(name),
    myThoughtCount(0)
// postcondition: ready to think        
{ }

void Thinker::ThinkAloud()
// postcondition: has thought    
{   
    if (myThoughtCount < 1)
    {   cout << "I'm thinking about thinking" << endl;
    }
    else
    {   cout << "Aha! I have found the answer!" << endl;
    }
    myThoughtCount++;
}

void Thinker::Reflect() const
// postcondition: has reflected
{   
    cout << "I'm worried about thinking too much" << endl;
}

string Thinker::Name() const
// postcondition: returns name        
{   
    return myName + ", a thinker";
}

void Think(Person & p)
// postcondition: p has thought and reflected once    
{  
   cout << "I am " << p.Name() << endl;
   p.ThinkAloud();
   p.Reflect();
}

int main()
{
    Simpleton s ("Sam");
    Thinker   t ("Terry");
    int k;
    for(k=0; k < 2; k++)
    {   Think(s);
        cout << "----" << endl << endl;
        Think(t);
        cout << "----" << endl << endl;
    }
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -