如何用C++中的枚举参数实例化对象?
问题描述:
我想用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
任何想法如何做到这一点?
答
修正如下,请参阅我的意见
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::
}
答
你的枚举,而你的主要功能是在类外。这就是它的原因。
所以从你的主函数引用枚举的正确的方法是:
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
部分,所以使用数据之前该枚举类型的严重性定义。
尝试'错误:: low',或'错误::严重:: low'。 – apalomer
将枚举定义移动到公共部分。 main()不能看到它,因为它是女贞。 –