2017-10-17 199 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部分,所以使用數據之前該枚舉類型的嚴重性定義。