2017-01-02 60 views
-1

我想创建一个抽象类(CellPhone)的动态数组,然后用类型Cell1和Cell2的不同对象填充它。创建一个抽象类的动态数组

我试着用动态数组和载体,但都给出一个错误:

创建的所有类和工作,但是在主:

Cell1 c1("Orange", "Hello! This is your friend Rima, call me when you can.", 0777170, "Sony"); 
Cell2 c2("Zain", "Call me ASAP, Sam", 0777777777, "blue", "wifi"); 
Cell1 c3("Omnia", "Let me know when you can pass by", 0711111111, "Samsung"); 

CellPhone *c[3]; 

*c[0]=&c1;  //Conversion to base class error 


vector<CellPhone*> cp; 
cp.push_back(&c1);  //Conversion to base class error 

我抬头等情况,但两者兼得我收到一个错误?为什么?以及如何解决它?

编辑:下面是参考类标头:

class CellPhone{ 
    private: 
    string branch, message; 
    int phoneNumber; 
public: 
    CellPhone(string, string, int); 
    virtual void receiveCall() = 0; 
    void receiveMessage(); 
    virtual void dial() = 0; 
    void setBranch(string); 
    void setMessage(string); 
    void setPhoneNumber(int); 
    string getBranch(); 
    string getMessage(); 
    int getPhoneNumber(); 

};

#include "CellPhone.h" 

class Cell1:CellPhone{ 
private: 
    string cameraType; 
    bool isCameraUsed; 
public: 
    Cell1(string, string, int, string); 
    void capture(); 
    void receiveCall(); 
    void dial(); 
    void setCameraType(string); 
    string getCameraType(); 

};

#include "Cell1.h" 

class Cell2:CellPhone{ 
private: 
     string wifi, bluetooth; 
public: 
    Cell2(string, string, int, string, string); 
void turnBluetoothOn(); 
void turnBlueToothOff(); 
void setWifi(string); 
void setBluetooth(string); 
string getWifi(); 
string getBluetooth(); 
void receiveCall(); 
void dial(); 

};

Cell2具有Cell1的引用,因为如果它没有,那么main中会出现类重新定义错误。

+0

如果没有CellPhone,Cell1,Cell2的定义,则无法回答。 http://stackoverflow.com/help/mcve – jpo38

+0

完成编辑 –

+0

如果您不选择继承,C++将默认为私有继承。这不是谨慎的。 – IInspectable

回答

2

只需将Cell2 : CellPhone替换为class Cell2 : public CellPhone即可。

否则,从Cell2CellPhone的转换不可访问(如果未指定,继承是private)。

编辑:如下所述,强烈建议您为CellPhone类声明一个虚拟析构函数(对于您在某个时间点擅长的任何类而言,建议这样做)。

+0

此外,您应该将99%的虚拟析构函数添加到CellPhone中的可能性很高。 – Frank

+0

@Frank:如果您将数组中的派生对象存储到基类指针,则可能性为100%。 OP是哪个。 – IInspectable

+0

只有当他从该向量中删除对象时才会出现这种情况,这是因为他在堆栈上创建了Cell对象。有一些罕见的边缘情况,其中虚拟析构函数不被期望/ waranted(并且通常涉及受保护的析构函数以避免问题),但在这里几乎肯定不是这种情况。 – Frank