我有一个抽象的基类“家具”,有1个子类“书柜”。
在handler.cpp中我创建了双指针;家具**家具。所以当我想添加东西时,我可以使用这样的东西;
void FurnitureHandler::addBookcase(string name, float price, int stock, string material, float height)
{
this->furniture[this->nrOfFurniture] = new Bookcase(name, price, stock, material, height);
this->nrOfFurniture++;
}
然而,“新”突出显示,我得到'错误C2243:'类型转换':从'书柜*'到'家具*'的转换存在,但是无法访问'。我需要做些什么来使其发挥作用?
码;
#ifndef __FURNITURE_H__
#define __FURNITURE_H__
#include<string>
#include<iostream>
using namespace std;
class Furniture
{
private:
string name;
float price;
int stock;
public:
void print()const;
virtual void printSpec()const =0;
public:
Furniture(string name = "", float price = 0.0f, int stock = 0);
virtual ~Furniture();
};
#endif
Furniture::Furniture(string name, float price, int stock)
{
this->name=name;
this->price=price;
this->stock=stock;
}
Furniture::~Furniture(){}
void Furniture::print()const
{
cout<<"All furnitures in memory:"<<endl;
this->printSpec();
}
#ifndef __BOOKCASE_H__
#define __BOOKCASE_H__
#include "Furniture.h"
class Bookcase : Furniture
{
private:
string material;
float height;
public:
Bookcase(string, float, int, string, float);
virtual ~Bookcase();
virtual void printSpec()const;
};
#endif
#include "Bookcase.h"
Bookcase::Bookcase(string name, float price, int stock, string material, float height) : Furniture(name, price, stock)
{
this->material = material;
this->height = height;
}
Bookcase::~Bookcase(){}
void Bookcase::printSpec()const
{
cout<<material<<", "<<height<<endl;
}
答案 0 :(得分:3)
更新
class Bookcase : Furniture
到
class Bookcase : public Furniture
默认情况下,C ++是私有继承的,这使得Bookcase has a Furniture
。
当您添加public inheritance
时,会生成Bookcase is a Furniture
答案 1 :(得分:2)
您使用的是私有而非公共继承,因此转换不是隐含的。
你必须写:
class Bookcase : public Furniture
// ^^^^^^
这类似于会员,默认情况下这些会员是私人的,除非您说public
。
如果使用Bookcase
关键字声明struct
,则默认为公开。
此外,使用std::vector
而不是这种危险的内存管理,你会好得多。
答案 2 :(得分:1)
使用Furniture**
使用this->furniture[this->nrOfFurniture] = ...
是危险的,因为在我看来,您不会检查是否可以插入最大数量的Furniture
({1}}你可能会覆盖你不拥有的内存。最好有std::vector
个push_back
元素。