what is the difference between with & and withou &

Discussion in 'C++' started by learning_C++, Sep 17, 2004.

  1. learning_C++

    learning_C++ Guest

    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;
    }
     
    learning_C++, Sep 17, 2004
    #1
    1. Advertisements

  2. 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.

    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.
     
    Karthik Kumar, Sep 17, 2004
    #2
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.