【问题标题】:How do I convert an object of Class B to Class C, if both Class B and C are derived of Class A in C++?如果 B 类和 C 类都派生自 C++ 中的 A 类,如何将 B 类的对象转换为 C 类?
【发布时间】: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


【解决方案1】:

从 RegularAccount 派生 VipAccount,这是有道理的,因为 Vip 应该拥有 Regular 拥有的一切。为 VipAccount 编写一个构造函数,它接受一个 RegularAccount 实例作为参数。在构造函数中将参数传递给基类RegularAccount。为了提升,创建一个以RegularAccount为参数的VipAccount实例,然后删除RegularAccount实例

【讨论】:

    猜你喜欢
    • 2019-11-18
    • 2021-12-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    相关资源
    最近更新 更多