The Student Class with Private Data fields (for lab)
标签(空格分隔): 程序设计实验 c++
本人学院
description
The class “Student” is declared as below.
Student {
public:
Student();
Student(int, const char*, int);
void set(int, const char*, int);
void print();
private:
int id;
char name[50];
int age;
};
Please implement the class to get expected output. You don’t need to submit the main function.
If the following main function is used, your implementation should get the expected output in the sample.
int main() {
Student std1, std2(123, "John Smith", 19), std3(124);
std1.set(100, "Bill Gates", 55);
std1.print();
std2.print();
std3.print();
return 0;
}
Sample Output:
Bill Gates (100) is 55 years old.
John Smith (123) is 19 years old.
No Name (124) is 0 years old.
Hint:
Private Data fields.
Default arguments.
main.cpp
#include <iostream>
#include "Student.h"
using std::cin;
int main() {
int test;
int id, nid, age;
char names[10][20] = { "Aries", "Bill gates",
"John Smith", "Blanton",
"Blanche", "Halley",
"Hamilton", "Rachel",
"Jacobs", "Jan"};
cin >> test;
cin >> id >> nid >> age;
if (test == 0) {
Student st;
st.print();
} else if (test == 1) {
Student st(id, names[nid], age);
st.print();
} else if (test == 2) {
Student st;
st.set(id, names[nid], age);
st.print();
} else if (test == 3) {
Student st(id);
st.print();
} else {
Student st(id, names[nid]);
st.print();
}
return 0;
}
读题
my answer
Student.h
#ifndef STUDENT_H
#define STUDENT_H
#include<iostream>
using namespace std;
class Student {
public:
Student(int = 0, const char* = "No Name", int = 0);
void set(int, const char*, int);
void print();
private:
int id;
char name[50];
int age;
};
Student::Student(int i, const char* n, int a) {
id = i;
age = a;
int j;
for (j = 0; *n != '\0'; j++) {
name[j] = *(n++);
}
name[j] = '\0';
}
void Student::set(int i, const char* n, int a) {
id = i;
age = a;
int j;
for (j = 0; *n != '\0'; j++) {
name[j] = *(n++);
}
name[j] = '\0';
}
void Student::print() {
cout << name << " (" << id << ")" << " is " << age << " years old." <<endl;
}
#endif
the standard answer
Student.h
#ifndef _STUDENT_H
#define _STUDENT_H
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
class Student {
public:
Student();
Student(int, const char*, int);
void set(int id_, const char* name_, int age_);
void print();
private:
int id;
char name[50];
int age;
};
Student::Student() {
id = 0;
snprintf(name, sizeof("No Name"), "No Name");
age = 0;
}
Student::Student(int id_, const char* name_ = "No Name", int age_ = 0) {
id = id_;
snprintf(name, sizeof(name), name_);
age = age_;
}
void Student::set(int id_, const char* name_, int age_) {
id = id_;
snprintf(name, sizeof(name), name_);
age = age_;
}
void Student::print() {
printf("%s (%d) is %d years old.\n", name, id, age);
}
#endif
反馈
snprintf()函数
将const char * 转换为 string
第一个参数为目的string的变量名
第二个参数为要复制的长度
第三个参数为源const char *的变量名