Dynamic binding a few [closed]
-
14-07-2021 - |
質問
Hi Experts can I do dynamic binding like this. objshapes is the parent class called Shape and Rectangle is the child class. I have a few child classes so depending which shape the user selects, I need to bind the correct shape to the objShapes. So i thought i can bind like this. but i getting an error.
Shape *objShapes[3];
objshapes[size]= &new Rectangle(3,lvaule,5)
//error: lvalue required as unary ‘&’ operand
Hope someone can assist. Thanks
IS THIS CORRECT
objshapes[size]= new Rectangle(3,lvaule,5)
解決
Shape *objShapes[3];
This declares objshapes as an array of 3 pointers-to-Shape.
objshapes[size]= &new Rectangle(3,lvaule,5)
This is non-sensical.
IS THIS CORRECT
objshapes[size]= new Rectangle(3,lvaule,5)
Yes1, that is correct. new
returns a pointer-to-Rectangle, which can be stored in a variable of type pointer-to-Shape. Since objshapes
is an array of pointers-to-Shape. objshapes[size]
is pointer-to-Shape -- which can accept a pointer-to-Rectangle.
1. Assuming that size
is convertable to an integral type, and has the value 0
, 1
, or 2
.
他のヒント
You would need an array or container of pointers, or preferably smart pointers, to the base class. For example:
std::vector<Shape*> objshapes;
objshapes.push_back(new Rectangle(3,lvaule,5));
objshapes.push_back(new Circle( args));
If you are using raw pointers instead of using smart pointers, you have to make sure to de-allocate the memory used by the shapes by calling delete
on all the pointers.
Edit since you are reluctant to use standard library containers, and you have clarified that you have an array of Shape*
, as opposed to an array of Shape
, then you can populate the array thus:
objshapes[idx]= new Rectangle(3,lvaule,5);