c++ 使用子类 'type cast' 错误

标签 c++ types casting

我有一个抽象基类“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/

相关文章:

c++ - 我怎么能转换成一个变量类名?

c++ - 将文件读入 vector ,我的输入函数有什么问题?

c++ - 内核崩溃 - 无法处理 000002c0 处的内核 NULL 指针取消引用

c++ - 数组下标的无效类型 'double [100][double]'

haskell - 在 Haskell 中使用类型别名的正确方法是什么

转换到 _Bool

java - 如何将顶部的 double 转换为 int 舍入

android - 完整性检查 - Android 模拟器中的 Cast 图标

c++ - 是否允许将空值插入 C++ std::map?

c++ - 共享库路径作为可执行目录