实验目的:
掌握静态、常量的应用,并掌握拷贝构造函数。
要求1:定义班级类,并在其内定义静态数据成员统计人数,并定义静态成员函数输出该数据;班级类中定义学生成员数据,并定义为链表方式;定义班级类的拷贝构造函数,并能复制班级内的学生成员。
要求2:分别设计函数参数、返回值为const修饰的指针形式,体会与一般函数的区别;
要求3:分别设计函数参数、返回值为const修饰的引用形式,体会与一般函数的区别。
#include <iostream>
using namespace std;
class clas
{
public:
struct Node//定义节点
{
string student;
Node* next = NULL;
};
Node* head = new Node;
static int num;//定义人数
static void pr()//输出人数
{
cout <<"当前人数为:" <<clas::num << endl;
}
clas()//构造函数
{
head->next = NULL;
cout << "node creat" << endl;
cout << "creat" << endl;
}
clas(const clas& c)//拷贝构造函数
{
temp=c.temp;
cout << "copy" << endl;
}
~clas()//析构函数
{
Node* node = head;
if (node != NULL)
{
delete node;
node = node->next;
}
cout << "delete" << endl;
}
void insert()
{
string newstudent[20];
int n;
cout << "请输入要输入学生的个数" << endl;
cin >> n;
for(int i=1;i<=n;i++)
{
cout << "请输入要输入的学生姓名:" << endl;
cin >> newstudent[i];
if (head == NULL)
{
Node* node = new Node;
node->student = newstudent[i];
node->next = NULL;
head = node;
}
else
{
Node* node = new Node;
node->student = newstudent[i];
node->next = head;
head = node;
}
clas::num++;
}
cout << "输入成功!" << endl;
}
void print()
{
if (num == 0)
cout << "没有学生!" << endl;
else
{
Node* node = head;
while (node!= NULL)
{
cout << node->student << endl;
node = node->next;
}
cout << "名单打印完成!" << endl;
}
}
void copy(clas& clas)
{
if (this == &clas)
return;
*this = clas;
}
private:
string temp;
};
int clas::num = 0;
int main()
{
clas clas1,clas2;
clas1.insert();
clas1.pr();
clas1.print();
clas2 = clas1;
cout << "after copy "<< endl;
clas2.pr();
clas2.print();
return 0;
}