【发布时间】:2021-04-15 03:03:20
【问题描述】:
我有一个名为“Customer”的基类,以及两个派生类“RegularAccount”和“VipAccount”。
现在,我想实现一个“promote”成员方法,如果满足某些条件,它允许将 RegularAccount 提升为 VipAccount。
如何在 C++ 中做到这一点?我试图在 RegularAccount 的“promote”方法中调用构造函数,但无法这样做。有没有办法在RegularAccount的成员函数中将RegularAccount对象中的所有数据复制到VipAccount对象中?
这是我的 RegularAccount 类的结构:
class RegularAccount : public Customer {
private:
public:
// Constructors && Destructors
RegularAccount();
RegularAccount(string id, string name, string address, string phoneNumber, int numberOfRental);
~RegularAccount();
// Member functions
void rentItem(const string itemName);
void returnItem(const string itemName);
void details();
void showRentalList();
void promote();
};
VipAccount 类:
class VipAccount : public Customer {
private:
int rewardPoints;
int freeRentItemAwarded;
public:
// Constructors
VipAccount();
VipAccount(string id, string name, string address, string phoneNumber, int numberOfRental);
// Member functions
void rentItem(const string itemName);
void returnItem(const string itemName);
void checkRewardPoints();
void details();
void showRentalList();
void promote();
};
【问题讨论】:
-
请提供最小的可重现示例。 VipAccount的定义是什么?
-
我是一名同时学习C和C++的学生。我对指针和继承概念非常陌生。
-
@StPiere 抱歉,我只是在 VipAccount 类的标题中输入了。
-
这里的问题是,如果你问 10 个 C++ 开发人员“什么是最好的方法来做
”,你会得到 11 个不同的答案。不幸的是,基于意见的问题与 stackoverflow.com 无关 -
我实现它的方法是在类中添加一个状态标志
enum class Status { regular, vip };和一个Status _status;成员变量。或者在State Pattern之后将另一个State接口成员变量用于可以根据需要设置或重置的具体State实现。
标签: c++ class inheritance type-conversion