sharetoy.cpp

来自「C++&datastructure书籍源码,以前外教提供现在与大家共享」· C++ 代码 · 共 72 行

CPP
72
字号
#include <iostream>
#include <string>
using namespace std;

// references and pointers for sharing, a prelude

class Toy   // kids play with toys
{
  public:
    Toy(const string& name);
    void Play();          // prints a message
    void BecomeBroken();  // the toy becomes broken
  private:
    string myName;
    bool   myIsWorking;
};

class Kid
{
  public:
    Kid(const string& name, Toy& toy);
    void   Play();        // plays with own toy
  private:
    string myName;
    Toy    myToy;
};

Toy::Toy(const string& name)
 : myName(name), myIsWorking(true)
{ }

void Toy::Play()
// post: toy is played with, message printed
{   
    if (myIsWorking)
    {   cout << "this " << myName << " is so fun :-)" << endl;
    }
    else
    {   cout << "this " << myName << " is broken :-(" << endl;
    }
}

void Toy::BecomeBroken()
// post: toy is broken
{
    myIsWorking = false;
    cout << endl << "oops, this " << myName << " just broke" << endl << endl;
}

Kid::Kid(const string& name,Toy& toy)
 : myName(name), myToy(toy)
{ }

void Kid::Play()
// post: kid plays and talks about it
{
   cout << "My name is " << myName << ", ";
   myToy.Play();
}

int main()
{
    Toy plaything("choo-choo train");
    Kid erich("erich", plaything);
    Kid katie("katie", plaything);
    
    erich.Play(); katie.Play();
    plaything.BecomeBroken();     // the toy is now broken
    erich.Play(); katie.Play();
    return 0;
}

⌨️ 快捷键说明

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