"Jamie Hankins" <Ja**********@discussions.microsoft.com> a écrit dans le
message de news:
37**********************************@microsoft.com...
| I'm probably being dense here. In the following situation:
|
| class Base {
| int x;
| int y;
| }
|
| class Decendant : Base {
| int z;
| }
|
| I need a function (constructor or whatever) in "Decendant" that will take
a
| "Base" and do a member-wise copy of "Base"'s members to itself. I know I
| could just copy each base member, but I know there's got to be a better
way.
|
| I tried the following constructor in Decendant:
|
| public Decendant(Base _base) : base(_base) {
| z = 0;
| }
|
| The problem is that "Base" doesn't have a constructor that takes an
instance
| of itself. I'd prefer not to modify "Base", if possible.
The best way of doing this is to add a copy constructor to the base class :
public class Base
{
private int x = 0;
private int y = 0;
... // public properties
public Base() { }
public Base(Base other)
{
x = other.x;
y = other.y;
}
}
public class Descendent : Base
{
private int z = 0;
... // public properties
public Descendent() : base() { }
public Descendent(Descendent other) : base(other)
{
z = other.z;
}
}
Why would you try and avoid modifying the base class ? Copy constructors are
a common feature in any hierarchy that implements IClonable; in fact, I
believe C++ creates a default copy constructor anyway.
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer