에 부모로부터 downcasting에 실패 내가 가지고있는 다음과 같은 부모의 자녀 간단한 클래스 :동적 캐스트는 아이
class BoundBases{
public:
virtual ~BoundBases() { }
};
// Rectangular Bounds for tree
class RectBounds : public BoundBases{
public:
// x, y center point
double x, y;
double w, h;
~RectBounds(){ }
// (_x, _y): center of rectangle bound. (_w, _h): width and height
RectBounds(double _x, double _y, double _w, double _h){
x = _x;
y = _y;
w = _w;
h = _h;
}
//... more functions
};
나는 또한 다음과 같은 기능 구조를 가지고 : 동적 캐스트는 비록 실패
void MyClass::init(BoundBases &bounds, std::vector<int> &colsPartitioned)
{
printf("init - new\n");
BoundBases * bPtr = &bounds;
RectBounds * rBounds = dynamic_cast<RectBounds *>(bPtr);
if(rBounds){
// do something
}else{
throw runtime_error("dynamic cast fail");
}
}
인수로 RectBounds 유형을 가진 함수를 호출합니다. 그 이유는 무엇입니까?
고정 : INIT를 호출 함수 값 BoundBases 통과
로서 다음 I 참조로 전달하는 특성을 변경하고 일
MyClass2::MyClass2(BoundBases boundBases, std::vector<int> colsPartitioned) { // creates new table
// set up partition
partScheme_ -> setColsPartitioned(colsPartitioned);
partScheme_ -> setBoundBases(boundBases);
partScheme_ -> init(boundBases, colsPartitioned);
}
. (& boundBases). 누군가 그 이유를 설명 할 수 있습니까? 나는 C/C++에 익숙하지 않다.
로 알려져있다? –
기본 생성자'BoundBases (double, double, double, double)'을 선언하지 않았기 때문일 수 있습니까? 결국, 캐스트를 수행하려면 유효한 완전한 객체가 필요합니다. –
init을 호출하는 함수/생성자가 BoundBases를 값이 아닌 참조로 전달 했으므로 고정했습니다. 왜 그게 달라 지니? –