带有set和get函数的学生类
C++ , Student Class with set and get functions
我试着为一个班级写一个学生的信息(姓名、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);
setName
以char
类型作为参数类型,如果您指的是字符串字面值"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;
- 使用运算符调用 void 函数时出错<set>
- 如何在构造函数参数中初始化"std::set"?
- 错误 C2676:std::set::const_iterator 没有运算符 + 函数?
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- 如何更改 std::set 的比较函数?
- 使用Set/Get-like方法或GetSet组合函数
- 通过函数指针对类内的 STL SET 使用自定义比较器
- 在类中使用映射并通过其他类的 get() 和 set() 函数访问值
- C++STL中set的'insert'函数的原理是什么?
- 如何键入定义一个专门的 std::set 模板,使用特定的比较函数实例化
- 为什么传递给函数 set::itrator 而不是 const_iterator 违反了一个定义规则?
- 错误:没有匹配的构造函数来初始化"set<int>"
- 使用 std::set 的 .begin() 和 .end() 函数会产生意想不到的结果
- 如何实例化多个 set 对象来测试 Set 类的各种构造函数和方法
- C ++设置与结构,set.find()函数使错误'invalid comparator'
- (Raspberry Pi 3)如何使用set()函数设置相机属性(来自raspicam/raspicam_cv.h)
- 将set函数(setter)标记为constexpr的目的是什么
- 函数对象无法识别它获得的参数(std::set<int>)
- 不能对 std::set<std::string, std::less 使用用户提供的比较函数<>>