sicily 7724. Class with id

Description

通过完成类的定义及其实 现:ClassWithCounter,使用下面提供的主函数,可以得到Sample Output中的输出。 鉴于大家还没有学习到static成员变量,在你的代码中可以采用全局变量做对象个数的统计。简单地讲,该全局变量初始为0,在 每个构造函数中自增1。在该类中,有一个成员变量记录着自己是第几个。

Output
在 默认的构造函数中输出如下内容:ClassWithCounter::ClassWithCounter(): id。(注意冒号与id间有一个空格,输出一行)。在析构函数中输出一下内 容:ClassWithCounter::~ClassWithCounter(): id。
 
Sample Input
 // 框架测试代码
#include "source.cpp"

int main(int argc, char *argv[]) {  
  ClassWithCounter cwc_0;
  ClassWithCounter *ptr_cwc_2;
  {
    ClassWithCounter cwc_1;
    ptr_cwc_2 = new ClassWithCounter;
  }

  delete ptr_cwc_2;
  return 0;
}
Sample Output
ClassWithCounter::ClassWithCounter(): 0
ClassWithCounter::ClassWithCounter(): 1
ClassWithCounter::ClassWithCounter(): 2
ClassWithCounter::~ClassWithCounter(): 1
ClassWithCounter::~ClassWithCounter(): 2
ClassWithCounter::~ClassWithCounter(): 0

给题目中的main函数做了下解释

 // 框架测试代码
#include "source.cpp" 

int main(int argc, char *argv[]) {  
  ClassWithCounter cwc_0; // 创建第一个对象cwc_0,调用构造函数后获得id为0并打印 
  ClassWithCounter *ptr_cwc_2; // 创建一个对象指针,目前指向空 
  {
    ClassWithCounter cwc_1; // 创建第二个对象cwc_1,调用构造函数后获得id为1并打印 
    ptr_cwc_2 = new ClassWithCounter; // 创建第三个对象并让指针ptr_cwc_2指过去,这个对象在创建时调用构造函数后获得id为2 
  } // 这时离开cwc_1的作用域,cwc_1的析构函数被调用,打印出其id即1 

  delete ptr_cwc_2; // 这时指针ptr_cwc_2所指向的对象被删除,cwc_2的析构函数被调用,打印出其id即2 
  return 0;// 这时退出main函数,离开cwc_0的作用域,cwc_0的析构函数被调用,打印出其id即0
}

类的实现,用了全局变量

View Code
 1 #include<iostream>
 2 using namespace std;
 3 
 4 int counter = 0; // 用来自增的id生成器 
 5 
 6 class ClassWithCounter
 7 {
 8 public:
 9     ClassWithCounter();
10     ~ClassWithCounter();
11 private:
12     int id;
13 };
14 
15 ClassWithCounter::ClassWithCounter()
16 {
17     id = counter; // 给这个新创建的对象赋予id 
18     cout << "ClassWithCounter::ClassWithCounter(): " << id << endl; //输出 
19     counter++; // id生成器自增,准备好为下一个创建的对象赋予一个比这个对象的id大1的id 
20 }
21 
22 ClassWithCounter::~ClassWithCounter()
23 {
24     cout << "ClassWithCounter::~ClassWithCounter(): " << id << endl;
25 }

 另一种实现,用了static变量,也可以AC

View Code
 1 #include<iostream>
 2 using namespace std;
 3 
 4 class ClassWithCounter
 5 {
 6 public:
 7     ClassWithCounter();
 8     ~ClassWithCounter();
 9 private:
10     int id;
11 };
12 
13 ClassWithCounter::ClassWithCounter()
14 {
15     static int counter = 0; 
16     id = counter; // 给这个新创建的对象赋予id 
17     cout << "ClassWithCounter::ClassWithCounter(): " << id << endl; //输出 
18     counter++; // id生成器自增,准备好为下一个创建的对象赋予一个比这个对象的id大1的id 
19 }
20 
21 ClassWithCounter::~ClassWithCounter()
22 {
23     cout << "ClassWithCounter::~ClassWithCounter(): " << id << endl;
24 }
原文地址:https://www.cnblogs.com/joyeecheung/p/2957977.html