C++ 构造函数中的枚举

Nik*_*ola 1 c++ oop constructor enumerator

我对 C++ 中的构造函数和 OOP 非常陌生,我遇到了以下问题。我尝试制作以下课程,但显然枚举器有问题。另外我想知道我是否可以以某种方式将 EUR 设置为默认选项。


class Amount
{
    // Todo 6.2
    // Implement class Amount
protected: 
    float Netto_;
    float Brutto_;
    enum tax_ { tax1 , tax2};
    enum Currency_ { EUR, USD }; 
    const float eur_to_usd = 1.13;
    const float usd_to_eur = 0.89;
    std::string Description_;

public:
    Amount(std::string Description , float Brutto, Currency_ Currency, tax_ taxtype) : Brutto_{Brutto} , Description_{Description}, Currency_{Currency}, tax_{taxtype} {} 

};

Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

"Currency_" is not a nonstatic data member or base class of class "Amount"
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mar*_*som 5

This line:

enum Currency_ { EUR, USD };
Run Code Online (Sandbox Code Playgroud)

is not declaring a member variable, it is declaring a type. Since there's no variable, you cannot initialize the variable. You need to break it into two lines:

enum Currency_ { EUR, USD };
Currency_ Currency_val;
Run Code Online (Sandbox Code Playgroud)

  • @1201ProgramAlarm 绝对正确。为了清楚起见,我仍然将枚举声明和变量声明分开。 (3认同)