2017-10-17 19 views
2

私は3つのパラメータでオブジェクト 'バグバグ'をインスタンス化しようとしています。そのうち1つは列挙子です。ここに私のクラスがあります:C++でenumパラメータを使用してオブジェクトをインスタンス化するにはどうすればよいですか?

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

enum定義をpublicセクションに移動します。 main()はそれがprivetであるので、それを見ることができません。 –

答えて

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 bg(3,"a", Bug::severity::low); 
+0

同じエラーメッセージが表示されました – Art

+0

プライベートセクションからパブリックに移動する必要があります –

+0

私はenumの重大度をpublicに移動し、メインでこれを使用しました:\t バグbg(3、 "a"、Bug ::低い)。 それは働いて、ありがとう! – Art

4

あなたの列挙型は、Bugクラス内に存在します。これはそれがいかにあるかである。

だからあなたの主な機能から列挙型を参照する正しい方法は次のようになります。

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

ただし、クラスのpublicセクション内の列挙型を定義する必要があります。これは現在、privateセクション内にあります。これにより、メイン関数がそれにアクセスできなくなります。

enumを、それを使用するプライベートメンバー変数とは別のクラス内の型として定義する必要があることにも注意してください。それが使われています前に、その列挙型の重症度が定義されているので、publicセクションでは、このクラスのprivateセクションの上にあることが必要であることを

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; 
}; 

注:だからあなたのクラスdefininitionはこのようなものになるはずです。

関連する問題