【发布时间】:2019-11-25 11:19:36
【问题描述】:
C++ 新手,我为“degree”创建了一个枚举,其中包含 3 种类型“SECURITY、NETWORKING、SOFTWARE”,当子类尝试使用枚举时,它们会返回类型错误。它具体寻找什么类型?
//Network Student Subclass
#include <string>
#include "degree.h"
#include "student.h"
class NetworkStudent : public Student //This class derives from Student
{
public:
NetworkStudent();
NetworkStudent(
string student_id,
string first_name,
string last_name,
string email,
double age,
double* days,
degree type
);
degree getdegree();
void setdegree(degree d);
void print();
~NetworkStudent();
};
//Enum with 3 Types
#include <string>
//The three types of degrees available
enum degree {SECURITY,NETWORKING,SOFTWARE};
static const std::string degreeTypeStrings[] = { "SECURITY","NETWORKING", "SOFTWARE" };
//Network Student definition with invalid type error for NETWORKING
#include "student.h"
#include "networkStudent.h"
using std::cout;
NetworkStudent::NetworkStudent()
{
//Right here is where I get the error on NETWORKING
setdegree(NETWORKING);
}
错误状态:“degree”类型的参数与“degree”类型的参数不兼容。我认为 degree 是一个枚举,而 NETWORKING 也是一个枚举。
【问题讨论】:
-
NETWORKING 不是枚举本身。它是枚举器列表中的一个条目。使用范围解析应该可以解决这个问题,例如 setdegree(degree::NETWORKING) (假设存在 setdegree 函数的实现)。查看此thread中的答案
-
感谢您的快速回复。似乎我需要在 NETWORKING 之前添加
degree::的“技巧”。是因为这个需要degree:::void setdegree(degree d); -
很高兴它成功了。请不要认为这是一些解决方法。基本上,范围解析运算符 (::) 帮助编译器找到定义的变量的确切位置,即在哪个范围内。这是执行此操作的标准 C++ 方式。在SO answer 中了解更多信息
-
感谢您花时间向新人解释。非常感谢!