首页 > 解决方案 > C++;这是确保正确数据成员初始化的正确方法吗?

问题描述

我有一个构造函数:

class Student{
    string name;
    string last_name;
    unsigned score;
...
   Student(string, string, int);

// Student.cpp

Student::Student(string name, string last_name, int score) : name(name), last_name(last_name)/
,score( score <= 0 ? 1 : score) {} // notice the 'score' initialization.

我想确保输入例如 Student s("name", "last", -1); 不会弄乱整个事情,因为学生的分数在 [1 , 5] 的区间内,并且分数是“无符号”数据类型。什么类型的分数真的无关紧要,我可以把它作为'int'或'int8_t'(用于节省内存)来解决问题,但我想知道是否有更好的方法来做到这一点?

谢谢大家 :)

标签: c++

解决方案


推荐阅读