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

📄 sharetoy.cpp

📁 C++&datastructure书籍源码,以前外教提供现在与大家共享
💻 CPP
字号:
#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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -