带有set和get函数的学生类

C++ , Student Class with set and get functions

本文关键字:函数 set get 带有      更新时间:2023-10-16

我试着为一个班级写一个学生的信息(姓名、IDno和学位),这个信息会打印在屏幕上;但我不知道错误在哪里?!

#include <iostream>
#include <conio.h>
using namespace std;
class Student {
private:
    char name;
    int idnumber;
    char degree;
public:
    Student(char,int,char);
    void setName(char n){name = n;}
    int getName(){return name;}
    void setIdnumber(char id){idnumber = id;}
    int getIdnumber(){return idnumber;}
    void setDegree(char d){degree = d;}
    int getDegree(){return degree;}
};
Student::Student(char n,int id,char d){
    name = n;
    idnumber = id;
    degree = d;
}
int main(){
    Student s1, s2;
    s1.setName(Sara);
    s1.setIdnumber(333);
    s1.setDegree(A);
    s2.setName(Jack);
    s2.setIdnumber(222);
    s2.setDegree(B);
    cout << "name: " << s1.getName() << ",IDnumber: " << s1.getIdnumber() << ",Degree: " <<      s1.getDegree() << endl;
    cout << "name: " << s2.getName() << ",IDnumber: " << s2.getIdnumber() << ",Degree: " << s2.getDegree() << endl;
    getch();
    return 0;
}

显然,您有以下问题:

 Student s1, s2;

这将尝试调用default constructor。但是,您定义了一个带3个参数的构造函数,这就限制了编译器为您生成默认构造函数,因此您将无法创建这些对象,从而有效地使后续成员函数调用失败。

s1.setName(Sara);

setNamechar类型作为参数类型,如果您指的是字符串字面值"Sara",那么您就有麻烦了。在其他函数调用中也可以发现类似的问题。你应该解决这个问题。

同时,你应该更倾向于使用member initialization list而不是在构造函数体中使用赋值来初始化成员。

  Student::Student(char n,int id,char d): name(n), idnumber(id), degree(d){}

确保你的成员是按照name, idnumber, degree的顺序声明的。

char是单个字符,而不是字符串。试着用std::string代替。

还可以声明字符串文字,用引号"包围字符串。如:

s1.setName("Sara");

同样,要使用std::string,您需要#include <string>

你的代码有几个问题

char name; 

name在这里只是一个字符字面值,所以当你试图传递字符串Sara给它时,它只会存储一个字面值。将name改为数组或指针

char name[10] or char *name

在传递名字的时候也用双引号,比如"Sara"。将函数中的所有形式参数更改为char数组或指针。

Student s1, s2;

在这里,当创建对象s1和s2时,它将调用默认构造函数,您没有提供,因此在代码中包含默认构造函数

Student(){}
s1.setDegree(A);

这里你试图传递一个文字而不是一个变量,所以引用它

s1.setDegree('A');

c++提供了字符串数据类型,它很容易使用wrt来char或char[],所以使用它。你可以像使用int, double这样的数据类型一样操作它。这将避免指定数组长度的麻烦,使用strcpy()来复制字符串。

string name;