View previous topic :: View next topic |
Author |
Message |
Maxlor
Joined: 22 Nov 2004 Posts: 1
|
Posted: Mon Nov 22, 2004 8:57 pm Post subject: copy on assignment |
|
|
I'm just starting with D, trying to figure out how it works. I've run into this thing here, and have been unable to find a solution online. Maybe you guys can explain things to me?
Lets say I have a class like this:
Code: | class Human {
this(uint age) { mAge = age; }
int age() { return mAge; }
void age(int age) { mAge = age; }
} |
Now, if I do this, joe will be a reference to peter, as if I had used the & operator in C++, ie, peter's age will be 30 as well at the end.
Code: | void main() {
Human peter = new Human(25);
Human joe = peter;
joe.age = 30;
printf("peter's age is ?i\n", peter.age);
return 0;
} |
Is there an easy way to have D make a copy, other than having to put the necessary copying code into the class itself? A shallow copy would do.
Hm... while I'm at it, another, smaller question. This doesn't work, obviously:
Code: | Human* jack = new Human(20); |
Is there a way to create an anonymous object and have its address stored in a pointer? |
|
Back to top |
|
|
Hohums
Joined: 08 Apr 2004 Posts: 71 Location: Western Australia
|
Posted: Fri Nov 26, 2004 8:33 am Post subject: Re: copy on assignment |
|
|
Maxlor wrote: | I'm just starting with D, trying to figure out how it works. I've run into this thing here, and have been unable to find a solution online. Maybe you guys can explain things to me?
Is there an easy way to have D make a copy, other than having to put the necessary copying code into the class itself? A shallow copy would do.
|
Use a struct instead (there are other ways but that is probably the simplest).
Maxlor wrote: |
Hm... while I'm at it, another, smaller question. This doesn't work, obviously:
Code: | Human* jack = new Human(20); |
Is there a way to create an anonymous object and have its address stored in a pointer? |
In D a class object is stored as its pointer. That is:
c++
Human* jack = new Human(20);
D
Human jack = new Human(20); _________________ http://badmama.com.au/~anderson/ |
|
Back to top |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|