By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,823 Members | 756 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,823 IT Pros & Developers. It's quick & easy.

what is the difference between with & and withou &

P: n/a
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;
}
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
learning_C++ wrote:
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.
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;
}

--
Karthik.
Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.