| |
 | Posted by Derek Parnell in reply to Trevor Parscal | Permalink Reply |
|
Derek Parnell 
Posted in reply to Trevor Parscal
| On Sun, 05 Jun 2005 22:28:15 -0700, Trevor Parscal wrote:
> OK, I don't really know what to call this, but I was hoping I could do something like this
>
> class FOO
> {
> /* Members */
> public:
> int Age;
>
> /* Functions */
> public:
> void Test()
> {
> this.Age++;
> };
> };
>
> class BAR : FOO
> {
> /* Members */
> public:
> char[] Name;
>
> /* Functions */
> public:
> void Test()
> {
> this.Name = "Trevor";
> this.Age++;
> };
> };
>
> and have an array of pointers to BAR classes
>
> BAR*[] bararray;
>
> and than have a pointer to an array of pointers to FOO classes
>
> FOO*[]* fooarray;
>
> and than be able to say
>
> fooarray = &bararray;
>
> Since BAR inherits FOO... I seem to either have done it wrong, or this is not allowed. Let me know if you have any clue as to the possiblities.
It is just saying you can't *implicitly* cast this. You can do it explicitly though...
<code>
import std.stdio;
class FOO
{
/* Members */
public:
int Age;
/* Functions */
public:
void Test()
{
this.Age++;
writefln("FOO age %d", Age);
};
};
class BAR : FOO
{
/* Members */
public:
char[] Name;
this(char[] pName, int pAge) { Name = pName.dup; Age = pAge; }
/* Functions */
public:
void Test()
{
this.Age++;
writefln("BAR age %d, name %s", Age, Name);
};
};
void main()
{
BAR*[] bararray;
FOO*[]* fooarray;
BAR b1 = new BAR("Derek Parnell", 42);
BAR b2 = new BAR("John Pilger", 17);
BAR b3 = new BAR("Roger Ramjet", 95);
bararray ~= &b1;
bararray ~= &b2;
bararray ~= &b3;
// Explicit casting!
fooarray = cast(FOO*[]*)&bararray;
foreach( FOO* f; *fooarray)
f.Test();
}
</code>
I run this program and get ...
BAR age 43, name Derek Parnell
BAR age 18, name John Pilger
BAR age 96, name Roger Ramjet
--
Derek
Melbourne, Australia
6/06/2005 4:31:01 PM
|