Alternative to friend functions?
Simen Kjærås
simen.kjaras at gmail.com
Tue Feb 18 13:05:29 UTC 2020
On Tuesday, 18 February 2020 at 12:43:22 UTC, Adnan wrote:
> class Wife(uint N) : Female {
> FemaleID engagedTo = -1;
> const MaleID[N] preferences;
>
> this(MaleID[N] preferences) {
> this.preferences = preferences;
> }
> }
>
> void engage(N)(ref Wife!N, wife, ref Husband!N husband) {
> // Here, I want to access both husband and wife's engaged_to
> }
Petar's answer covers your question, so I won't elaborate on
that, but I'd like to point out that as Wife and Husband are
classes, you probably don't intend to take them by ref - classes
are always by ref in D, so you're effectively passing a reference
to a reference to a class in `engage`.
Basically:
class Foo {
int n;
}
void fun(Foo f) {
f.n = 3;
// Local copy of the reference - does not modify other
references.
f = null;
}
void gun(ref Foo f) {
f = null;
}
unittest {
Foo f = new Foo();
Foo g = f;
f.n = 17;
// f and g point to the same object:
assert(f.n == 17);
assert(g.n == 17);
fun(f);
// fun() changed the object that both f and g point to:
assert(f.n == 3);
assert(g.n == 3);
gun(f);
// gun() changed f to no longer point at the same object, but
left g untouched:
assert(f is null);
assert(g !is null);
assert(g.n == 3);
}
--
Simen
More information about the Digitalmars-d-learn
mailing list