C++面向对象程序中的获取和设置方法

Get and Set Methods in C++ OOP

本文关键字:设置 方法 获取 面向对象 程序 C++      更新时间:2023-10-16

在我的计算机科学类中,头文件中有一个枚举值,而get和set函数有问题。我对C++还很陌生。这是我头文件的一部分:

enum class SchoolType {
    Elementary = 1,
    Secondary = 2
};
class School : public Institution
{
    public:
        // There are a couple more values here
    SchoolType GetSchoolType();
    void SetSchoolType(SchoolType typeSchool);
};

这是我.cpp文件的一部分:

SchoolType GetTypeSchool()
{
    return this->_typeSchool;
}
void SetTypeSchool(SchoolType typeSchool)
{
}

但是"this"会带来一个错误,并表示"this"只能在非静态成员函数中使用。如何使该函数工作?我的计算机老师告诉我,这就是我应该如何编码get函数,但我仍然不明白,是不是我在标题中做错了什么?

对于.cpp文件,应该有:

SchoolType School::GetSchoolType() {
    return this->_typeSchool;
}
void School::SetSchoolType(SchoolType typeSchool) {
    // Insert code here...
}

基本上,在C++中,当定义成员函数时,您需要指定函数属于哪个类(在本例中为School),否则编译器不会将其视为任何类的一部分。您还需要保持方法名称的一致性(GetSchoolTypeGetTypeSchool)。