【问题标题】:What is the correct way of designing the promote() mechanism in C++在C++中设计promote()机制的正确方法是什么
【发布时间】:2021-07-30 21:45:52
【问题描述】:

我尝试用 C++ 构建一个客户经理程序。在我的程序中,有Customer类(基类),Guest(派生自客户),VIP(派生自Guest),main中有一个vector数组来存储所有客户。因此,如果我想从向量中提升一个 Guest 对象,那么最好的方法是什么。我确实考虑过低调的方法,但还有其他方法可以将客人提升为 VIP。

Class Customer {
protected:
    string name;
public:
    Customer();
    Customer(string name);
};

Class Guest : public Customer {
public:
    Guest();
    Guest(string name);
}

Class VIP : public Guest {
private:
    int VIPPoints;
public:
    VIP();
    VIP(string name);
}

【问题讨论】:

  • 创建一个接受Guest&&VIP ctor
  • 缺乏对他们行为差异的可靠解释,看起来包含bool guest; std::optional<int> VIPpoints; 的类可以完成这项工作。
  • 有很多方法可以做到这一点。例如,我个人可能只有一个Customer 类,带有std::vector<Customer> guestsstd::vector<Customer> vips 以及一些数据结构来跟踪点。如果需要 OOP,我可能会将客户的“状态”拆分为一个单独的类型,以便 Customer 有一个 Status,其状态可能是 VIPGUEST,或者甚至可能使Status 具有继承层次结构,Customer 没有继承树。

标签: c++ oop inheritance polymorphism abstraction


【解决方案1】:

您可以创建 CustomerWrappper 类,该类将结合来宾和 VIP 和枚举来识别客户类型。

class CustomerWrapper {
public:
    enum CustomerType
    {
        guest,
        vip
    };  
    
    CustomerWrapper(const Guest& guest);
    CustomerWrapper(const VIP& vip);
    CustomerWrapper& operator=(const Guest& guest);
    CustomerWrapper& operator=(const VIP& vip);

private:
    CustomerType type;
    union {
        Guest guest;
        VIP vip;
    };
};

然后你可以创建这个包装器的向量

vector<CustomerWrapper*> customers;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2017-03-05
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多