我对最小特权原则有疑问。创建对象时递增成员
I have problem with least privilege principle. incrementing a member when an object is created
我想跟踪系统中的学生人数,所以我的想法是在“StudentController”class 中创建一个静态数据成员,名为“ _numOfStudents”并使用 Student 的构造函数递增它,但它不起作用,所以我将它移到“Student”class 中,并在构造函数的帮助下创建 Student 对象时使数字递增。问题是:知道那里有多少学生不是 Student class 的事,因此违反了最小特权原则。我怎样才能更好地跟踪学生对象的数量。
Student(string firstName, string lastName, int age,vector<float>&subjects)//Student conctructor
{
SetFirstName(firstName);
setLastName(lastName);
SetAge(age);
SetMarks(subjects);
this->m_id++;
StudentController::_numberOfStudents++;
}
class StudentController//this is where i declared the static data member
{
private:
list<Student> _students;
public:
static int _numberOfStudents;
StudentController() {};
StudentController(list<Student>& st) :_students(st) {};
}
}
};
int StudentController::_numberOfStudents = 0;
当您尝试在构造函数中执行 StudentController::_numberOfStudents++;
时,StudentController
class 尚未定义,因此编译器不知道 class 和它的静态成员。
也许跟踪学生不应该是 Student
class 本身的作用。相反,它应该是一个单独的 Classroom
对象的角色:
struct Student;
struct Classroom {
void add(Student&) {
m_count++;
}
size_t count() const { return m_count; }
private:
size_t m_count{0};
};
struct Student {
Student(Classroom& classroom) {
classroom.add(*this);
}
};
int main()
{
Classroom classroom;
Student alice{classroom};
Student bob{classroom};
assert(classroom.count() == 2);
}
我想跟踪系统中的学生人数,所以我的想法是在“StudentController”class 中创建一个静态数据成员,名为“ _numOfStudents”并使用 Student 的构造函数递增它,但它不起作用,所以我将它移到“Student”class 中,并在构造函数的帮助下创建 Student 对象时使数字递增。问题是:知道那里有多少学生不是 Student class 的事,因此违反了最小特权原则。我怎样才能更好地跟踪学生对象的数量。
Student(string firstName, string lastName, int age,vector<float>&subjects)//Student conctructor
{
SetFirstName(firstName);
setLastName(lastName);
SetAge(age);
SetMarks(subjects);
this->m_id++;
StudentController::_numberOfStudents++;
}
class StudentController//this is where i declared the static data member
{
private:
list<Student> _students;
public:
static int _numberOfStudents;
StudentController() {};
StudentController(list<Student>& st) :_students(st) {};
}
}
};
int StudentController::_numberOfStudents = 0;
当您尝试在构造函数中执行 StudentController::_numberOfStudents++;
时,StudentController
class 尚未定义,因此编译器不知道 class 和它的静态成员。
也许跟踪学生不应该是 Student
class 本身的作用。相反,它应该是一个单独的 Classroom
对象的角色:
struct Student;
struct Classroom {
void add(Student&) {
m_count++;
}
size_t count() const { return m_count; }
private:
size_t m_count{0};
};
struct Student {
Student(Classroom& classroom) {
classroom.add(*this);
}
};
int main()
{
Classroom classroom;
Student alice{classroom};
Student bob{classroom};
assert(classroom.count() == 2);
}