【问题标题】:use of enum in a constructor c++在构造函数c ++中使用枚举
【发布时间】:2018-09-24 13:10:13
【问题描述】:

我正在尝试创建一个具有两个值的类“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?

【问题讨论】:

  • Apple 继承并包含Color(顺便说一句,这是空类)?
  • enum class Color { red, green };
  • Color != Color::color.
  • 让 Apple 继承 Color 是没有意义的。苹果一种颜色,但它们不是颜色。

标签: c++ enums


【解决方案1】:

class Apple 中的Color c; 成员指的是Color 基类,而不是其中定义的color 枚举器。话虽如此,从设计的角度来看,你似乎是在继承苹果的颜色。我相信您的意图是让每个 Apple 实例都保存一个颜色值。为此,您想要composition,而不是继承——因为苹果不是颜色,它is-afruit :) 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 Color 在构造时为你的Apple 以防未指定,那么你可以为它编写声明:

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

所以你可以这样做:

const Apple a1{10};

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

【讨论】:

  • 还有一个问题:当没有给定颜色时,如何在构造函数中将苹果的默认颜色设置为 g
【解决方案2】:

正如 cmets 已经指出的那样,您正在创建一个(空)类 Color 并在其中定义一个作用域枚举。所有这些都是不必要的;你需要的只是枚举。将您的课程Color 替换为

enum class Color{r,g};

并且不要在Apple 声明中使用: public Color

无关,但有必要让您的代码按书面方式运行:您将 Apple 变量声明为 const,但随后在其上调用非const 方法。为了完成这项工作,您需要您的 n_return 看起来像这样。

int n_return() const {return n;}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 2015-07-09
    • 2011-07-03
    相关资源
    最近更新 更多