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

📄 howmany2.cpp

📁 ThinkingC++中文版
💻 CPP
字号:
//: C11:HowMany2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// The copy-constructor
#include <iostream>
#include <string>
using namespace std;


class HowMany2 {
  string name; // Object identifier
  static int  objectCount;

public:
  HowMany2(const string& id = "") : name(id) 	//id is the name of current object
  {
    ++objectCount;
    print("本次由带参构造函数HowMany2(const string& id = "")建立的对象是:");
  }	 

  ~HowMany2() 
  {
    --objectCount;
    print("~HowMany2()本次删除的对象是:");
  }

  // The copy-constructor:
  HowMany2(const HowMany2& com) : name(com.name) 
  {
    name += "_copy";
    ++objectCount;
    print("本次由拷贝构造函数HowMany2(const HowMany2&)建立的对象是:");
  }

  void print(const string& msg )  const
  {
    if(msg.size() != 0) 
      cout << msg << endl;
    cout << '\t' << name << ": " << "objectCount = " << objectCount << endl;
  }

};

int  HowMany2::objectCount = 0;

// Pass and return BY VALUE:
HowMany2 f(HowMany2 x) 
{
  cout << "Returning from ......f()......" << endl;
  return x;	   //before the local variable x can be destroyed (it goes out of scope at the end of the function), it must be copied into the return value. 
}
//After the object(return value) is returned, but before the function ends, the local object “h copy” is destroyed.


HowMany2& f1(HowMany2& x)
{
  cout << "Returning from ......f1()......" << endl;
  return x;	   
}



void main() 
{
  HowMany2 h1("h1"); // the first thing that happens is that the normal constructor is called for h1,
  HowMany2 h2(h1);
  cout << "1--------------------------------------" << endl;
  HowMany2 h3(f(h1)); //第一步: 用h1初始化f()的形参x(h1_copy);进入函数f();返回前用x初始化h3(h1_copy_copy);销毁x 
  cout << "1--------------------------------------" << endl;
  
  h3.print("关于对象h3: ");
  cout << "2--------------------------------------" << endl;
  f(h1);	//第一步: 用h1初始化f()的形参x(h1_copy);进入函数f();返回前把x拷贝到一个匿名对象(h1_copy_copy);销毁x,销毁匿名对象
  cout << "2--------------------------------------" << endl;

  
  cout << "3--------------------------------------" << endl;
  f1(h1);	
  cout << "3--------------------------------------" << endl;



  cout << "after leaving the main()......." << endl;
} ///:~

⌨️ 快捷键说明

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