howmany.cpp

来自「ThinkingC++中文版」· C++ 代码 · 共 48 行

CPP
48
字号
//: C11:HowMany.cpp
// A class that counts its objects
#include <iostream>
#include <string>
using namespace std;

int objectcount = 0;
void print(const string& msg = "");

class HowMany {
public:
  HowMany()  //The constructor increments the count each time an object is created, 
  { 
	  objectcount++; 
  }
  
  ~HowMany() //the destructor decrements it.
  {
    objectcount--;
    ::print("~HowMany()");
  }
};
 
void print(const string& msg) 
{
    if(msg.size() != 0) 
		cout << msg << ": ";
    cout << "objectCount = " << objectcount << endl;
}


// Pass and return BY VALUE:
HowMany f(HowMany x) {
  print("x argument inside f()");
  return x;
}

void main() 
{
  HowMany h1;   //call the default constructor
  print("after construction of h1");
  HowMany h2(h1);//等价于 HowMany h2 = h1; 
  print("after construction of h2");

  HowMany h4 = f(h1); //how to create a new object from an existing object?
  print("after call to f()");
} ///:~

⌨️ 快捷键说明

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