gpt4 book ai didi

c++ - 显示传递给 C++ 类构造函数的枚举值

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:54:15 24 4
gpt4 key购买 nike

我编写了一个简短的测试代码,用于将枚举值传递给类构造函数。它适用于编译器。但是,输出很奇怪。 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;
}

最佳答案

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

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

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

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

关于c++ - 显示传递给 C++ 类构造函数的枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22585839/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com