[fortran]CLASS(c_father) :: myclass IF (EXISTS(myclass%attribA)) THEN PRINT *, myclass%attribA END IF[/fortran]
連結已複製
Create a parameter enumeration (unique codes for) your attribute types.
Have as a requirement for all child classes to have a function that returns a reference/pointer/value to the member variable in the child that represents the attribute parameter .OR. return NULL .OR. return a default reference/value (argument passed into the query function).
With this technique the child need not know future additions to the attributeparameter enumeration table and the child need not know the operation to be performed by the caller. This does requie each child to have a query attribute (get reference to attribute) function.
Jim Dempsey
In your code, you could then do a SELECT TYPE looking for CLASS(c_fatherA).
You really need this SELECT TYPE or something equivalent. The designator myclass%attribA, is never legal when myclass is declared CLASS(c_father), because the c_father has no component named attribA. In order to be able to legally write this designator, you need to use SELECT TYPE to establish a local myclass which is effectively declared with a type (or class) that has attribA.
No, it is quite different. Putting attribA into c_father would take space in every class c_father object. Putting a type-bound procedure in class_father adds space only to the dispatch table shared by all the objects of the same type. As a result this approach is much more memory efficient.
Using type-bound procedures is the other classic way of address the kind of problem you present, as it is the other way to start with an object of a general class and end up with an object that is syntactically recognized to be of a more specific type or class (so you can actually access attribA).
You might want to combine this approach with the intermediate class approach by putting a "do nothing" operation in c_father and overriding it with the operation that manipulates attribA in c_fatherA.
[fortran]FUNCTION DoExist(AttribCode) RESULT(ThePointer)[/fortran]
The designator myclass%attribA, is never legal when myclass is declared CLASS(c_father)
[fortran]try PRINT *, c_father%attribA catch (e) PRINT *, 'Doesnt have attribA'[/fortran]
