题目描述
已知主函数和Tutor类,请根据输入输出完成STU类定义
输入
输入一个参数,作为全局变量IDs的初始值,用于输出结果提示,看样例
输出
输入:100
输出:
Construct student Tom
Construct student Tom_copy
Construct tutor 100
Calling fuc()
Construct student Tom_copy_copy
In function fuc()
Destruct tutor 101
Destruct student Tom_copy_copy
Destruct tutor 101
Destruct student Tom_copy
Destruct student Tom
给定代码:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
//填空实现类STU的定义
//其他代码如下
int IDs; //全局变量,用于输出结果提示
class Tutor {
private:
STU stu;
public:
Tutor(STU & s): stu(s)
{ cout<<"Construct tutor "<<IDs<<endl; }
~Tutor()
{ cout<<"Destruct tutor "<<IDs<<endl; }
};
void fuc(Tutor x)
{ cout<<"In function fuc()"<<endl; }
int main()
{ cin>>IDs;
STU s1("Tom"); //输入学生姓名Tom
Tutor t1(s1);
IDs++;
cout<<"Calling fuc()"<<endl;
fuc(t1);
return 0;
}
分析给定代码:
主函数:将Tom传入STU类,将s1传入t1,第一次拷贝,将t1传入空函数,引用t1时第二次拷贝。
AC代码:
class STU
{
private:
string s;
public:
STU(string h)//将Tom传入STU类私有成员s
{
s=h;
cout<<"Construct student "<<s<<endl;
}
STU(const STU &m)//拷贝构造
{
s=m.s+"_copy";
cout<<"Construct student "<<s<<endl;
}
~STU()
{
cout<<"Destruct student "<<s<<endl;
}
};