what is the difference between with & and withou &

L

learning_C++

Hi,
I compiled some code. In the function friend ostream&
operator<<(ostream& os, const complex c);

I use the later argument complex c and complex& c. I can get the same
values and there is no error when I compile this code.
Please tell me the difference.


#include <iostream>
using namespace std;

class complex{
double re, im;
friend ostream& operator<<(ostream& os, const complex c);

public:
complex(double r, double i):re(r), im(i){}
complex operator+(complex& c){
return complex(re + c.re, im + c.im);
};
//complex operator*(complex);
};

ostream& operator<<(ostream& os, const complex c){
os <<"("<<c.re<<","<<c.im<<")";
return os;
}
int main(){
complex a =complex(1, 3.1);
complex b=complex(1.2, 2);
complex c=b;
a =b+c;
cout<<a<<endl;
return 0;
}
 
K

Karthik Kumar

learning_C++ said:
Hi,
I compiled some code. In the function friend ostream&
operator<<(ostream& os, const complex c);

I use the later argument complex c and complex& c. I can get the same
values and there is no error when I compile this code.
Please tell me the difference.

Google for 'references' in C++.

Briefly, 'complex & c' in a function parameter list , indicates you are
passing the reference instead of copy of the object.

#include <iostream>
using namespace std;

class complex{
double re, im;
friend ostream& operator<<(ostream& os, const complex c);

public:
complex(double r, double i):re(r), im(i){}
complex operator+(complex& c){
return complex(re + c.re, im + c.im);
};
//complex operator*(complex);
};

ostream& operator<<(ostream& os, const complex c){
os <<"("<<c.re<<","<<c.im<<")";
return os;
}

Well - there is a STL library called complex, that would much more
than what you had mentioned before. You can use that if you are writing
an application.
 

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
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top