why I have compile error

D

David

Hi,

why I have compile error as follows?
r.cpp: In function `int main ()':
r.cpp:40: call of overloaded `change(Demo &)' is ambiguous
r.cpp:11: candidates are: void Demo::change (Demo)
r.cpp:23: void Demo::change (Demo &)

-------------program
#include <iostream>

class Demo{
public:
int x, y, z;
public:
Demo(int i, int j, int k){
x =i; y=j; z =k;
}

void change(Demo t){
t.x = 1;
t.y = 2;
t.z = 3;
}

void change(Demo *t){
t->x = 1;
t->y = 2;
t->z = 3;
}

void change(Demo &t){
t.x = 1;
t.y = 2;
t.z = 3;
}

void print(Demo t){
cout << "x=" << t.x <<endl;
cout << "y=" << t.y <<endl;
cout << "z=" << t.z <<endl;
}

};

int main(){
Demo num(10, 20 ,30);
Demo &tt = num;
tt.change(tt);
tt.print(tt);
}
-----------
 
M

Moritz Beller

On 2 Sep 2004 12:34:00 -0700
why I have compile error as follows?

Because the compiler cannot conclude from your call of the function in
the code whether it should use the reference version or the other one.

The only solution I can think of is renaming this feature/function if
you really need it.

best regards
Moritz Beller
 
D

DaKoadMunky

void change(Demo t){
t.x = 1;
t.y = 2;
t.z = 3;
}

Are you sure you even need/want this?

It is not going to change the Demo object passed to it...it is going to change
a copy of the Demo object passed to it.
 
W

Will Twentyman

David said:
Hi,

why I have compile error as follows?
r.cpp: In function `int main ()':
r.cpp:40: call of overloaded `change(Demo &)' is ambiguous
r.cpp:11: candidates are: void Demo::change (Demo)
r.cpp:23: void Demo::change (Demo &)

The & on line 23 does not tell Demo what type of variable it will
receive as a parameter, but that it should use a reference to that
parameter instead of a copy of the parameter inside Demo::change.

In other words, lines 11 and 23 specify identical parameters (variable
or reference to a variable), and are therefor ambiguous.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,175
Messages
2,570,946
Members
47,495
Latest member
Jack William

Latest Threads

Top