gpt4 book ai didi

c++ - 没有指针的多态性

转载 作者:行者123 更新时间:2023-11-30 01:19:36 24 4
gpt4 key购买 nike

我试图创建一个抽象类并使用它来确定购买的支付方式,使用多态性。我尝试了一些不同的东西,但我仍然无法让它按我想要的方式工作。这是代码:

class PaymentMethod {
public:
PaymentMethod() {}
virtual std::string getPaymentMethod() = 0;
};

class PayWithMoney : public PaymentMethod {
public:
PayWithMoney() {}
virtual std::string getPaymentMethod() {
std::string paymentMethod = "Payed with Money";
return paymentMethod;
}
};

class PayWithDebitCard : public PaymentMethod {
public:
PayWithDebitCard() {}
virtual std::string getPaymentMethod() {
std::string paymentMethod = "Payed with Debit Card";
return paymentMethod;
}
};

我还有一个类(class):

class Purchase {
private:
something
PaymentMethod _paymentMethod;
public:
Purchase(something, const PaymentMethod& paymentMethod)

但我不断收到编译器错误,提示 cannot declare field ‘Purchase::_paymentMethod’ to be of abstract type ‘PaymentMethod’

我猜我将不得不使用指针,对吧?

我认为我应该尽量避免 newdelete 除非使用长生命周期对象,但由于 PaymentMethod 是一个抽象类,我不能用它作为类(class)成员......我错了吗?

最佳答案

应该尽量避免newdelete,这是绝对正确的。

方法如下:

#include <memory>       // for std::unique_ptr
#include <utility> // for std::move

class Purchase
{
Purchase(std::unique_ptr<PaymentMethod> payment_method)
: payment_method_(std::move(payment_method))
{ }

std::unique_ptr<PaymentMethod> payment_method_;

public:
static Purchase MakeDebitCardPurchase()
{
return Purchase(std::make_unique<PayWithDebitCard>());
}

static Purchase MakeCashPurchase()
{
return Purchase(std::make_unique<PayWithCash>());
}
};

用法:

auto purchase = Purchase::MakeCashPurchase();

请注意 std::make_unique 尚不存在,因此您可能不得不说:

return Purchase(std::unique_ptr<PaymentMethod>(new PayWithCash));

这是唯一一次你必须说 new,一旦 std::make_unique 在标准库中可用,即使这样也会消失。

作为此设计的一个额外好处,您现在可以轻松添加测试代码,例如模拟付款方式。

关于c++ - 没有指针的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20661197/

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