【发布时间】:2017-01-02 20:41:38
【问题描述】:
我正在尝试创建一个抽象类 (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 中会出现类重定义错误。
【问题讨论】:
-
没有CellPhone、Cell1、Cell2的定义,是无法回答的。 stackoverflow.com/help/mcve
-
如果不选择继承,C++默认为私有继承。这不谨慎。
-
另外,您的
CellPhone类缺少虚拟析构函数。
标签: c++ arrays class dynamic abstract