c++静态与常量

实验目的:
掌握静态、常量的应用,并掌握拷贝构造函数。
要求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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值