friendly.cpp

来自「Thinking in C++ 2nd edition source code 」· C++ 代码 · 共 53 行

CPP
53
字号
//: C03:Friendly.cpp
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// Demonstration of friend functions.
// The synchronize() function has arguments from both watch
// and microwave_oven.  The first time synchronize() is declared
// as a friend in watch, the compiler won't know that
// microwave_oven exists unless we declare it's name first:
class MicrowaveOven;

class Watch {
  int time;  // A measure of time
  int alarm;  // When the alarm goes off
  int date;   // Other things a Watch should know
public:
  // Constructor sets starting state:
  Watch() { time = alarm = date = 0; }
  void tick() { time++; } // Very simple transition
  // Declare a friend function:
  // (see text for meaning of '&')
  friend void synchronize(Watch &, MicrowaveOven &);
};

class MicrowaveOven {
  int time;
  int start_time;
  int stop_time;
  int intensity;
public:
  MicrowaveOven() {
    time = 0;
    start_time = stop_time = 0;
    intensity = 0;
  }
  void tick() { time++; }
  friend void synchronize(Watch &, MicrowaveOven &);
};

void synchronize(Watch & objA, MicrowaveOven & objB) {
  objA.time = objB.time = 15;  // Set both to a common state
}

int main() {
  Watch que_hora;
  MicrowaveOven nuke;
  que_hora.tick();
  que_hora.tick();
  nuke.tick();
  synchronize(que_hora,nuke);
} ///:~

⌨️ 快捷键说明

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