在构造函数C中使用枚举

时间:2018-09-24 13:10:13

标签: c++ enums

我正在尝试创建一个具有两个值的类“ Apple” 1. int n 2.枚举颜色

但是我的代码不起作用,并且出现“初始化时没有匹配的构造器”错误

我不知道什么是最好的方法。

#include <iostream>
#include<stdexcept>

using namespace std;

class Color{
public:
   enum color{r,g};
};

class Apple: public Color {
    int n;
    Color c;
public:
    Apple(int n,Color color){
        if(n<0)throw runtime_error("");
        this->n=n;
        this->c=color;
    }
    int n_return(){return n;}
};
int main(){
    try{
        const Apple a1{10,Color::g};
        cout << a1.n_return();}
    catch(runtime_error&){
        cout<<"ER\n";
    }
    return 0;
}

我不想更改main中的任何内容。

此外,在没有颜色的情况下,如何在构造函数中将苹果的默认颜色设置为g?

2 个答案:

答案 0 :(得分:2)

正如评论所指出的那样,您正在创建一个(空)类Color,并在其中定义了一个有范围的枚举。所有这些都是不必要的废话。您需要的只是枚举。将您的课程Color替换为

enum class Color{r,g};

并且不要在: public Color声明中执行Apple

不相关,但必须使您的代码正常工作:将Apple变量声明为const,然后在其上调用非const方法。为了使这项工作有效,您需要n_return看起来像这样。

int n_return() const {return n;}

请注意此处的const关键字,以允许在const变量上使用该方法。

答案 1 :(得分:2)

您在Color c;中的class Apple成员引用的是Color基类,而不是其中定义的color枚举器。话虽如此,从设计的角度来看,您似乎是从颜色中继承了苹果 。我相信您打算让每个Apple实例拥有一个颜色值。为此,您想要composition,而不是继承-因为 Apple 不是颜色,它是is-a水果:) has-a颜色。

此外, n_return()必须是一种const方法,以便您能够从const实例调用它。

这与您的原始代码最接近,可以填补与语法和设计有关的问题,因此您可以轻松地区分出差异。 main()保持不变:

#include <iostream>
#include<stdexcept>

using namespace std;

enum class Color{r,g};

class Apple{
    int n;
    Color c;
public:
    Apple(int n,Color color){
        if(n<0)throw runtime_error("");
        this->n=n;
        this->c=color;
    }
    int n_return() const {return n;}
};
int main(){
    try{
        const Apple a1{10,Color::g};
        cout << a1.n_return();}
    catch(runtime_error&){
        cout<<"ER\n";
    }
    return 0;
}

请注意,我已将您的enum更改为enum class。您可以read about here使用该邮件的一般原因。

如果要在构造时set the default ColorApple进行设置(如果未指定的话),则可以这样编写声明:

// Apple has Color `g` by default
Apple(int n,Color color = Color::g){//...

因此您可以这样做:

const Apple a1{10};

并获得您的Color::g彩色苹果。