2017-10-17 201 views
2

我想用3个参数实例化一个对象的Bug Bug,其中一个是枚举器。这里是我的班级:如何用C++中的枚举参数实例化对象?

class Bug 
{ 
private: 
    int Id; 
    string description; 
    enum severity { low, medium, severe} s; 

public: 
    Bug(void); 
    Bug(int id, string descr, severity x) 
       :Id(id), description(descr), s(x) 
    {} 

    void printDetails() 
    { 
     cout<< "Severity level:" <<s<< " Description: " <<description<<" ID= " 
     <<Id<< endl; 
    } 
    ~Bug(void); 

};

这是我的main.cpp:

#include "Bug.h" 
    int main(){ 

    Bug bg(3,"a", low);//Error message: identifier "low" is undefined 

    return 0; 
    } 

,当我加入此行的主要

enum severity { low, medium, severe}; 

错误信息已更改为这样:

 Bug bg(3,"a", low);//Error message: no instance of constructor "Bug::bug" matches the argument list 

任何想法如何做到这一点?

+0

尝试'错误:: low',或'错误::严重:: low'。 – apalomer

+0

将枚举定义移动到公共部分。 main()不能看到它,因为它是女贞。 –

回答

0

修正如下,请参阅我的意见


class Bug 
{ 


public: 
    // If you intent to use severity outside class , better make it public 
    enum severity { low, medium, severe} ; 

    Bug(void); 
    Bug(int id, string descr, severity x) 
       :Id(id), description(descr), s(x) 
    {} 

    void printDetails() 
    { 
     cout<< "Severity level:" <<s<< " Description: " <<description<<" ID= " 
     <<Id<< endl; 
    } 

    ~Bug() 
    { 
     // Fix your constructor, they don't have void parameter and must have a body 
    } 

    // Moving private section, just to use the severity declaration in public section 
private: 
    int Id; 
    string description; 
    severity s ; // use an instance of severity for internal use 
}; 

int main() 
{ 
    Bug bg(3,"a", Bug::low); // now use severity values using Bug:: 


} 
0

移动枚举公共区域,并尝试使用方法:将Bug类内部存在

Bug bg(3,"a", Bug::severity::low); 
+0

我试过了,我得到了同样的错误信息 – Art

+0

您需要将它从私有区域移动到公共区域 –

+0

我将枚举严重性移到了公共主目录中,并在主目录中使用了这个:\t Bug bg(3,“a”,Bug ::低); 它的工作,谢谢! – Art

4

你的枚举,而你的主要功能是在类外。这就是它的原因。

所以从你的主函数引用枚举的正确的方法是:

Bug bg(3,"a", Bug::low);

但是,您需要定义类的public段内的枚举。它目前位于private部分,这将阻止主功能访问它。

请注意,您还需要将enum定义为与使用它的私有成员变量分离的类中的类型。所以,你的类defininition应该成为这样的事情:

class Bug 
{ 
public: 
    typedef enum {low, medium, severe} severity; 
    Bug(void); 
    Bug(int id, string descr, severity x) 
       :Id(id), description(descr), s(x) 
    {} 

    void printDetails() 
    { 
     cout<< "Severity level:" <<s<< " Description: " <<description<<" ID= " 
     <<Id<< endl; 
    } 
    ~Bug(void); 

private: 
    int Id; 
    string description; 
    severity s; 
}; 

注意,public部分需要高于这个类中的private部分,所以使用数据之前该枚举类型的严重性定义。