2014-04-02 2 views
1

나는 1 개의 서브 클래스 "책장"을 가진 추상적 인 baseclass "가구"를 가지고있다.C++ 하위 유형 'cast'사용 오류

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

도처에'this->'를 쓰지 않아도됩니다. – Salgar

+0

@Salgar : 그는 ctor-initialiser를 제대로 사용하지 않아서 사용했습니다. 게다가 좋은 스타일이라고 생각하는 학교가 있습니다. 나는 어느 쪽이든에 대한 의견을 갖고 있지 않습니다. –

+0

'__FURNITURE_H__'처럼 [예약 된 이름] (http://stackoverflow.com/questions/228783)을 사용하지 마십시오. –

답변

3

갱신

class Bookcase : Furniture 

기본적으로

class Bookcase : public Furniture 

에, C++은 Bookcase has a Furniture하게되는, 상속 비공개입니다. 당신이 public inheritance를 추가 할 때 나에게 것 때문에

, 그것은 그 안에 삽입 할 수 Furniture 's의 최대 개수가있는 경우 확인하지 않는 것이 this->furniture[this->nrOfFurniture] = ...를 사용하는 것이 위험 Furniture**Bookcase is a Furniture

1

한다 (자신이 소유하지 않은 메모리를 덮어 쓸 수도 있습니다). push_back 요소가있는 경우 std::vector을 사용하는 것이 좋습니다.

2

공개 상속이 아닌 개인 상법을 사용하고 있으므로 변환이 암시 적이 지 않습니다.

class Bookcase : public Furniture 
//    ^^^^^^ 

이것은 당신이 public 말을하지 않는 한 기본적으로 비공개 있습니다 회원에 대한 같습니다 :

당신은 작성해야합니다.

Bookcase 여기서 struct 키워드로 선언 된 경우 기본값은 공개되었을 것입니다.

또한 위험한 메모리 관리가 아닌 std::vector을 사용하면 훨씬 편리 할 것입니다.