class AutoVehicle: public RoadVehicle {/* ... */};
class Aircraft: public Vehicle {/* ... */};
class Helicopter: public Aircraft {/* ... */};
Vehicle parking_lot[1000];
If you gona to compile this source file, you will got errors and warnings like this:
images
The reason why we got error is that Vihecle is a base class, member function @weight and @start is pure virtual function. With the = 0 in the declaration, we declare that that pure virtual function could without definitaion. Only the class which is inherit from base class Vihecle.
So, the object Vehicle is not existed and we can’t define an array of that type.
If we change the virtual function into non-virtual function, we could pass the compile process.
But it’s very dangerous.
Eg, if we delete all pure virtual functions in Vehicle, what would happen?
1
2
3
4
5
Vehicle parking_lot[1000];
Automobile x = /* ... */
Parking_lot[num_vihicles++] = x;
The answer is that there would be a cast on @x. @x is class Automobile which inhiret from base class Vehicle. @x will be cast into class Vehicle and then assign to object Parking_lot[num_vihicles]. In the process of casing, @x will lost anything which is not in Vehicle.
More explicit, the array Parking_lot is an array of class Vehicle but not Automobile.
It’s time release our scheme to solve that problem.
You may noticed that the key point of our solution is to use the class to represent a concept.
We defined a contructor without any parameters, so we define an array of this type of class.
If you have understand what we have done, you may feel excited. Yes, we create a container which could be used to represent any type of classes which are have relationships of inhiretance.
parking_lot[num_vehicles++] = x; is equal to parking_lot[num_vehicles++] = VehicleSurrogate(x);
This statement create a copy of object @x and attach @VehicleSurrogate onto object @x. If we destory elements in @parking_lot, the corresponding copy will be deleted.
Finally, you have know that why this techonology named Surrogate.
The objects in this type of class could be used to represent others class objects which are have completly relationships of inhiretance.
Margaret Heafield Hamilton who is a very famous computer scientist, systems engineer, and business owner. Picture blew there is that hamilton during the Apollo Program.
近期评论