题目描述
请实现一个老鼠类,下面已给出代码模板,请根据main函数中对该类的操作,补充类实现部分完成代码。
该类有个公有静态变量num记录该类的所有对象数,主函数将会在不同语句之后输出对象数,只有正确地实现该类,保证num正确记录该类的对象数,才能输出正确的结果
其他地方没什么难度,主要是拷贝构造函数的运用.
注意
静态数据变量和拷贝函数的关系
拷贝后的构造函数赋值方式(这个题里没用到)
另外别忘了析构函数,平时用的少
还记得拷贝构造函数时的书写格式(&的位置,参数名字要大写)
配合 C++拷贝构造函数详解
#include "stdafx.h"
#include <iostream>
using namespace std;
class Mouse {
/* Your code here! */
public:
static int num;//由于是静态数据变量,默认拷贝是不认的.
Mouse();
Mouse(const Mouse&);//拷贝~
~Mouse()
{
num--;
}
};
int Mouse::num = 0;
Mouse::Mouse()
{
Mouse::num++;
}
Mouse::Mouse(const Mouse& M)
{
Mouse::num++;
}
void fn(Mouse m);
int main()
{
Mouse::num = 0;
Mouse a;
cout << Mouse::num << endl;
Mouse b(a);//等价于 Mouse b=a;
cout << Mouse::num << endl;
for (int i = 0; i < 10; ++i)
{
Mouse x;
cout << Mouse::num << endl;
}
fn(a);
cout << Mouse::num << endl;
return 0;
}
void fn(Mouse m)
{
cout << Mouse::num << endl;
Mouse n(m);
cout << Mouse::num << endl;
}