[C++学生类] The Student Class

丁鸿云
2023-12-01

[C++学生类] The Student Class

题目

 With a class "Student" declared as below:
 class Student {
public:
  int id;
  char name[50]; // Data field
  int age; // Data field
  Student();
  Student(int, char*, int);
};

You are required to implement the class functions and also two other functions used to process Student objects, which can get output as specified later.

void set(Student &, int, char*, int);
void print(Student);

1) You don't need to submit the main function.
2) You don't need to include the header file for class declaration by yourself.

输入

输出

Steven Gates (100) is 61 years old.
Larry Jordan (123) is 18 years old.
No Name (124) is 0 years old.

代码答案

main.cpp

#include <iostream>
#include <cstring>
#include "source.h"
using namespace std;


int main()
{

  Student std1, std2(123, "Larry Jordan", 18), std3(124);
  set(std1, 100, "Steven Gates", 61);
  print(std1);
  print(std2);
  print(std3);
  return 0;
}

source.h

#include <iostream>
#include <cstring>
using namespace std;
class Student
{
public:
  int id;
  char name[50]; // Data field
  int age; // Data field
  Student();
  Student(int, char*, int);
  //void set(int, char*, int);
  //void print();
};

void set(Student &, int, char*, int);
void print(Student);

Student::Student() {
    id=0;
    strcpy(name,"No Name");
    age=0;
}
Student::Student(int pid,char* pname="No Name",int page=0) {
    id=pid;
    strcpy(name,pname);
    age=page;
}
void set(Student&stu,int id,char*name,int age) {
    stu.id=id;
    stu.age=age;
    strcpy(stu.name,name);
}
void print(Student stu) {
    cout<< stu.name <<" ("<<stu.id<<") "<<"is "<<stu.age<<" years old."<<endl;
}
 类似资料: