【问题标题】:Passing through subclass as parameter using this使用 this 传递子类作为参数
【发布时间】:2019-11-08 19:35:45
【问题描述】:

我正在尝试使用this 将一个类作为参数发送给构造函数,并且我在两个不同的类CasinoDealerGambler 中执行此操作,所以在接收端StandAction 我有一个构造函数接受 2 个参数 performerhand

Performer 是类,但我将参数作为CasinoDealerGambler 都继承的基类; Player 基类。

我想既然Gambler类或CasinoDealer类继承了Player基类,我可以使用this发送类,接收端有Player* performer作为参数,并且知道哪个类创建了对象,但显然这不起作用,那我该怎么做呢?

我省略了一些包含和不重要的函数,以尽量减少发布的代码。

赌徒.cpp

Action* Gambler::GetAction(int input) {
    Action* action = nullptr;
    switch (input) {
    case 1:
        action = new StandAction(this, new Hand());
        break;
    default:
        break;
    }
    return action;
}

播放器.h

class Player {
public:
    virtual Action* DecideNextMove() = 0;
};

StandAction.h

class StandAction : public Action {
public:
    StandAction(Player* performer, Hand hand);
    void Execute();
};

StandAction.cpp

StandAction::StandAction(Player* performer, Hand hand) : Action(performer, hand) {

}

它抱怨没有构造函数的实例与参数列表匹配。我想如果我发送的类继承了Player,可以作为参数传递,并在接收端使用Player* performer

C++ no instance of constructor matches the argument list
            argument types are: (Gambler *, Hand *)

【问题讨论】:

  • 查看另一个参数及其参数。

标签: c++ visual-c++ arguments parameter-passing


【解决方案1】:

嗯,这个错误对我来说很清楚。 new Hand() 返回 Hand*,而不是 StandAction 构造函数所需的 Hand。所以你可能想要new StandAction(this,Hand());

请不要使用new,使用std::unique_ptr<T>并按值返回std::unique_ptr<Action>。除非您知道自己在做什么,否则最好仅将原始指针用于非拥有关系。

编辑:使用unique_ptr

std::unique_ptr<Action> Gambler::GetAction(int input) {
    std::unique_ptr<Action> action;
    switch (input) {
    case 1:
        action = std::make_unique<StandAction>(this, Hand());
        break;
    default:
        break;
    }
    return action;
}

由于您在这两种情况下都将StandAction* 转换为Action*,因此请确保Action::~Action() 是虚拟的。

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多