C++学习历程(二)多文件编译

1.首先创建一个类的头文件,便于以后对类的使用。包含类的成员变量和成员函数。stu.h
#ifndef _STU_H_
#define _STU_H_

class Student
{
    char m_name[20];
    int m_age;
    Student *m_next;

public:
    Student();
    Student(char *name,int age);
    void SetNext(Student *n);
    Student *GetNext();
    char *GetName();
    int GetAge();
};

class Manage
{
    Student *m_first;
    int m_sum;
public:
    Manage();
    void Init();
    void Insert();
    void Show();
    void List();
    void Delete();
};

#endif

2.创建另一个文件,用于编写类中的成员函数。stu.cpp

#include "stu.h"
#include <cstring>
#include <iostream>
#include <cstdlib>

using namespace std;

Student::Student()
{
    m_age = 0; 
}

Student::Student(char *name,int age)
{
    strcpy(m_name,name);
    m_age = age;
}

void Student::SetNext(Student *n)
{
    m_next = n;
}

Student *Student::GetNext()
{
    return m_next;
}

char *Student::GetName()
{
    return m_name;
}

int Student::GetAge()
{
    return m_age;
}


Manage::Manage()
{
    m_first = NULL;              //带头结点的链表
    m_sum = 0;                  //标记结点
}

void Manage::Init()
{
    m_first = new Student;
}

void Manage::Show()
{
    cout << "1.Insert    2.List" << endl;
    cout << "3.Delete    4.exit" << endl;
}

void Manage::Insert()
{
    char name[20];
    int age;
    Student *p = m_first;

    cout << "Input name and age :" << endl;
    cin >> name >> age;

    Student *s = new Student(name,age);

    for(int i = 0;i < m_sum;i++)
    {
        p = p -> GetNext();            //p指向最后一个结点的头
    }
    p -> SetNext(s);                    //最后一个结点的尾接上新结点s
    m_sum++;
}

void Manage::List()
{
    Student *p = m_first -> GetNext();  //指向头结点的下一个结点的头
    for(int i = 0;i < m_sum;i++)
    {
        cout << p -> GetName() << " " << p -> GetAge() << endl;
        p = p -> GetNext();
    }
}

3.最后创建main函数文件,只需要调用其他文件中的函数,简洁明了。main.cpp

#include "stu.h"
#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char **argv)
{
    int choice;
    Manage M;
    M.Init();

    while(1)
    {
        M.Show();
        cin >> choice;

        switch(choice)
        {
            case 1 : M.Insert(); break;
            case 2 : M.List()  ; break;
            //case 3 : M_delete(); break;
            case 4 : exit(1)   ; break;
        }
    }

    return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值