我有一个抽象基类“Furniture”和 1 个子类“Bookcase”。
在 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++;
}
但是,"new"已突出显示,我收到“错误 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;
}
最佳答案
更新
class Bookcase : Furniture
到
class Bookcase : public Furniture
默认情况下,C++ 是私有(private)继承的,这使得Bookcase has a Furniture
。
当您添加公共(public)继承
时,它使Bookcase is a Furniture
关于c++ 使用子类 'type cast' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22806951/