gpt4 book ai didi

c++ - C++ OOP 中的获取和设置方法

转载 作者:太空狗 更新时间:2023-10-29 20:56:09 25 4
gpt4 key购买 nike

在我的计算机科学课上,我在头文件中有一个枚举值,但我在使用 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 函数的代码,但我仍然不明白,是不是我在 header 中做错了什么?

最佳答案

对于 .cpp 文件,您应该:

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

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

关于c++ - C++ OOP 中的获取和设置方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com