【问题标题】:How do I fix this "argument of type incompatible with parameter" error?如何解决此“类型参数与参数不兼容”错误?
【发布时间】: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 中了解更多信息
  • 感谢您花时间向新人解释。非常感谢!

标签: c++ class enums


【解决方案1】:

正如 cmets 中的其他人所提到的,您在这里寻找的实际上是 degree::NETWORKING。原因是NETWORKING 是枚举degree 的一部分,而不是在全局空间中。因此,您需要指定您打算使用哪个NETWORKING

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2021-12-18
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    相关资源
    最近更新 更多