2

我有一个PersonCustomerand继承的抽象接口SalesPersonPerson包含两个派生类的每个成员函数的纯虚函数,这两个派生类需要通过对基类的引用(多态性)相互调用。这允许我解耦我的类型,对吗?

如何停止我的派生类继承其他派生类的纯虚函数并成为抽象类,而不用在我的派生类中使用伪非纯虚函数镜像兄弟类重写函数?

class Person {
public:
    virtual int const GetNumberOfPurchases() const = 0;
    virtual long const GetId() const = 0;
    virtual void AddPurchase() = 0;
    virtual void DisplayCustomerDetails() const = 0;
    virtual void DisplaySalesPersonStats() = 0;
    virtual void SetContact(Person * SalesP) = 0;
};

class SalesPerson: public Person {
private:
    long const id;                    // Assumption: Sales people never change their ID
    Person *bestCustomer;
    Person *worstCustomer;
    vector<Person *> v_Client;
    virtual int const GetNumberOfPurchases() const { return 0; }; // dummy to avoid inheriting pure virtual function
    virtual void AddPurchase() {}
    virtual void DisplayCustomerDetails() const {}
    virtual void SetContact(Person * SalesP) {}
public:
    SalesPerson();
    virtual ~SalesPerson(){};
    Person const *GetBestCustomer() const;
    Person const *GetWorstCustomer() const;
    virtual long const GetId() const { return id; }
    void DisplaySalesPersonStats();
    float const CalculateMeanAverageSales();
    void SignUpCustomer(Person * aCustomer);
    void RegisterSale(long customerId);
    void CalculateBestAndWorstCustomers();
    void DisplayClientList();
    long GenerateSalesPersonKey();
};

class Customer: public Person{
private:
    long ID;
    int birthYear;
    bool isCurrentMember;
    unsigned numberOfPurchases;
    const Person *contact;       // Assumption: Each Customer has a single assigned contact SalesPerson
    virtual void DisplaySalesPersonStats() {} // Dummy to avoid inheriting pure virtual from Person
public:
    Customer(const int aBirthYear);
    virtual ~Customer() {}
    virtual long const GetId() const;
    int const GetBirthYear() const;
    void SetBirthYear(int aBirthYear);
    bool const GetIsCurrentMember() const;
    void ToggleIsCurrentMember();
    virtual int const GetNumberOfPurchases() const;
    virtual void AddPurchase();
    virtual void DisplayCustomerDetails() const;
    virtual void SetContact(Person * SalesP);
    long GenerateCustomerKey();
};
4

1 回答 1

2

你不能。一旦定义了抽象基类,就需要在它的后代中实现所有功能。否则编译器将不知道你想做什么。想象:

class Person
{
public:
   virtual void beCustomer() = 0;
   virtual void doSales() = 0;
};

class Customer : public Person
{ 
public:
   virtual void beCustomer() { doStuff(); }
}

使用此代码:

Person* p;
p = new Customer();
p.doSales();

现在,p.doSales();是一个完全有效的调用,因为您承诺 anyPersondoSales()方法吗?

唯一的解决方案是使用空方法而不是抽象方法:

class Person
{
public:
   virtual void beCustomer() {};
   virtual void doSales() {};
};
于 2013-08-12T02:23:40.210 回答