Yingli Yan
Yingli Yan

Reputation: 69

How to use a function in class correctly in C++ OOP

Sorry for such a not good title. Now please see my detailed question.

Actually, I faced with such an exercise problem: Definite a class CComplex for complex number. Then, definite two objects c1 and c2 in CComplex . Next, use a constructor to initialize c1 and c2. After that, give c1's value to c2.

My code is as followed:

#include<iostream>
using namespace std;

class CComplex
{
public:
    CComplex(int real1,int image1)
    {
        real=real1;
        image=image1;
    }
    CComplex(CComplex &c)
    {
        real=c.real;
        image=c.image;
    }
public:
    void Display(void)
    {
        cout<<real<<"+"<<image<<"i"<<endl;
    }
private:
    int real,image;
};

int main()
{
    CComplex c1(10,20);
    CComplex c2(0,0);
    c1.Display();
    c2.Display();
    CComplex c2(c1);
    c2.Display();
    return 0;
}

It has an error that 'c2' : redefinition.

Then, I changed CComplex c2(c1); into c2(c1);.

At this time, it has an error that error C2064: term does not evaluate to a function

Now, I don't know how to correct it.

PS: I know that using c2=c1 can achieve the goal straightly. But, I really want to know how to correct almost based on my code above. Also, I want to know if there is any better ways to convey a complex number.

Upvotes: 0

Views: 158

Answers (3)

4pie0
4pie0

Reputation: 29724

yes, you cannot create c2 object and than use copy constructor on it, because copy constructor creates NEW object, you can use it directly

CComplex c1(10,20);
c1.Display();
CComplex c2(c1);
c2.Display();

to create c2 as a copy of c1 or if you want to assign value to object use something like this:

CComplex c1(10,20);
CComplex c2(0,0);
c1.Display();
c2.Display();
c2=c1;
c2.Display();

also you should provide your own assignnment operator for such purposes

    CComplex& operator=(const CComplex& other){
    if (this != &other) // protect against invalid self-assignment
    {
        // possible operations if needed:
        // 1: allocate new memory and copy the elements
        // 2: deallocate old memory
        // 3: assign the new memory to the object

    }
    // to support chained assignment operators (a=b=c), always return *this
    return *this;
    }

Upvotes: 0

JBentley
JBentley

Reputation: 6260

I'm not sure exactly what your goal is, since you already know the correct answer. However, perhaps this "looks" more like your incorrect version, and is better for you?

c2 = CComplex(c1);

Upvotes: 0

NPE
NPE

Reputation: 500167

I know that using c2=c1 can achieve the goal straightly

It will work, and will do its job marvellously. I therefore don't see what you're trying to achieve with more convoluted (and incorrect) syntax.

Upvotes: 2

Related Questions