簡體   English   中英

在構造函數C中使用枚舉

[英]use of enum in a constructor c++

我正在嘗試創建一個具有兩個值的“ 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;
}

我不想更改任何主要內容。

另外,當沒有顏色時,如何在構造函數中將apple的默認顏色設置為g?

您的Color c; class Apple成員是指Color基類,而不是其內部定義的color枚舉器。 話雖如此,從設計的角度來看, 您似乎是從Color 繼承了Apple 我相信您打算讓每個Apple實例都擁有一個顏色值。 為此,您需要組成而不是繼承 - 蘋果不是一種顏色 ,而是-一種水果:) 具有一種顏色。

此外, 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 您可以在此處閱讀的一般原因。

如果要在構建時為Apple 設置默認 Color (如果未指定),則可以為它編寫聲明,如下所示:

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

因此,您可以執行以下操作:

const Apple a1{10};

並獲取您的Color::g彩色蘋果。

正如評論中已經指出的那樣,您正在創建一個(空)類Color並在其中定義了一個范圍內的枚舉。 所有這些都是不必要的廢話。 您需要的只是枚舉。 將您的班級Color替換為

enum class Color{r,g};

並且不要這樣做: public Color Apple聲明中的: public Color

不相關,但必須使您的代碼正常工作:將Apple變量聲明為const ,然后在其上調用非const方法。 為了使此工作有效,您需要n_return看起來像這樣。

int n_return() const {return n;}

注意此處的const關鍵字,以允許在const變量上使用該方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM