Using class inside itself

T

Tatu Portin

I have a class:

class Complex {
public:
double x, y;

Complex () {x = 0.0; y = 0.0;};

Complex operator * (Complex);

Complex operator / (Complex);

Complex conj (void);
private:
};

Complex Complex::eek:perator / (Complex a) {

Complex b;

b = me * a;

/* by me, I mean this class, so that x == me.x and y == me.y */

}


So how I reference to this class whom inside I am?

So that I don't need to redefine multiplying again when using it within
the class.
 
D

Donovan Rebbechi

I have a class:

class Complex {
public:
double x, y;

these should be private
Complex () {x = 0.0; y = 0.0;};

Complex() : x(0.0),y(0.0) {}
Complex operator * (Complex);

operator* should be a non-member.

Make operator*= a member. Pass arguments by const ref,
not by value

e.g. Complex& operator*= (const Complex& z) {
double xnew = x*z.x-y*z.y; y = x*z.y+y*z.x; x = xnew; return *this;
}
Complex Complex::eek:perator / (Complex a) {

Complex b;

b = me * a;

/* by me, I mean this class, so that x == me.x and y == me.y */

No, you mean this object. Use the "this" keyword which references a pointer
to the calling object. So to multiply the calling object by a, write:
b = *this * a;

btw, the above code does not do division. You need to multiply by the inverse
of a which is the complex conjugate over the length squared

Cheers,
 
R

Rolf Magnus

Tatu said:
I have a class:

class Complex {
public:
double x, y;

Complex () {x = 0.0; y = 0.0;};

Complex operator * (Complex);

Complex operator / (Complex);

Complex conj (void);
private:
};

Complex Complex::eek:perator / (Complex a) {

Complex b;

b = me * a;

/* by me, I mean this class, so that x == me.x and y == me.y */

}


So how I reference to this class whom inside I am?

You mean "object", not "class". You can access it through an implicitly
defined pointer named 'this'. So your function becomes:

Complex Complex::eek:perator / (Complex a) {

Complex b;

b = *this * a;
//...
}

Another way is to call the operator by its "full" name, like:

b = operator*(a);

But i'd recommend to not write operators like / as member operators. Rather
make them non-members.
 

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

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top