【问题标题】:Display the enum value that is passed to c++ class constructor显示传递给 c++ 类构造函数的枚举值
【发布时间】:2014-03-23 01:16:29
【问题描述】:

我编写了一个简短的测试代码,用于将枚举值传递给类构造函数。它适用于编译器。但是,输出很奇怪。 Display() 不显示枚举值。它只显示“当前代理的策略是”。这段代码有什么问题?谢谢!

#include <iostream>

using namespace std;

class Agent
{
public:
    enum Strat {BuyandHold, Momentum, TA};
    Agent(Strat strategy=BuyandHold);
    ~Agent();
    void Display();
private:
    Strat strategy;
};

Agent::Agent(Strat strategy)
{
    strategy = strategy;
}

Agent::~Agent()
{
    cout << "Bye!" << endl;
}

void Agent::Display()
{
    cout << "The strategy of the current agent is ";
    switch(strategy){
    case BuyandHold : cout << "BuyandHold." << endl; break;
    case Momentum : cout << "Momentum." << endl; break;
    case TA : cout << "TA." << endl; break;
    }
}

int main()
{
    Agent a(Agent::TA);
    a.Display();
    return 0;
}

【问题讨论】:

    标签: c++ class enums


    【解决方案1】:

    您需要将本地参数名称声明与类成员区分开来。只需为您的初始化参数提供一个不同的名称:

    Agent::Agent(Strat strategy_)
    : strategy(strategy_) {}
    

    我更喜欢 _ 后缀来标记类成员变量或参数名称,因为任何一种方式都符合标准(使用诸如 _ 前缀将不会,而其他任何像例如 m_ 前缀类成员变量是笨拙的恕我直言)。

    另请注意:
    我一直在使用成员初始化器列表来分配类成员变量,这是大多数用例的正确选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-12
      • 2012-10-29
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      相关资源
      最近更新 更多