howmany2.cpp

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

CPP
61
字号
//: C11:HowMany2.cpp
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// The copy-constructor
#include <fstream>
#include <cstring>
using namespace std;
ofstream out("HowMany2.out");

class HowMany2 {
  enum { bufsize = 30 };
  char id[bufsize]; // Object identifier
  static int object_count;
public:
  HowMany2(const char* ID = 0) {
    if(ID) strncpy(id, ID, bufsize);
    else *id = 0;
    ++object_count;
    print("HowMany2()");
  }
  // The copy-constructor:
  HowMany2(const HowMany2& h) {
    strncpy(id, h.id, bufsize);
    strncat(id, " copy", bufsize - strlen(id));
    ++object_count;
    print("HowMany2(HowMany2&)");
  }
  // Can't be static (printing id):
  void print(const char* msg = 0) const {
    if(msg) out << msg << endl;
    out << '\t' << id << ": "
        << "object_count = "
        << object_count << endl;
  }
  ~HowMany2() {
    --object_count;
    print("~HowMany2()");
  }
};

int HowMany2::object_count = 0;

// Pass and return BY VALUE:
HowMany2 f(HowMany2 x) {
  x.print("x argument inside f()");
  out << "returning from f()" << endl;
  return x;
}

int main() {
  HowMany2 h("h");
  out << "entering f()" << endl;
  HowMany2 h2 = f(h);
  h2.print("h2 after call to f()");
  out << "call f(), no return value" << endl;
  f(h);
  out << "after call to f()" << endl;
} ///:~

⌨️ 快捷键说明

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