LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C: Add an operator to a struct (https://www.linuxquestions.org/questions/programming-9/c-add-an-operator-to-a-struct-229041/)

drigz 09-10-2004 02:55 PM

C: Add an operator to a struct
 
Is there anyway I can achieve make an operator (eg +) for a struct I've defined myself. For example:
Code:

typedef struct complex {
        double a;
        double b;
};

main(){
struct complex foo,bar,foobar;
foo.a = 4; foo.b = 7; //foo = 4 + 7j
bar.a = -3; bar.b = 2; //bar = 2j - 3
foobar = foo+bar; //foobar = 1 + 9j
}

I know that it can be done in C++, but I don't fancy learning the whole classes making thing just for this.

Thank you.

EDIT: Also, if there a clever way to set a struct, like foo = {4,5}; instead of invidually setting both members. I tried the above, but DJGPP didn't like it when not used during the original creation (struct complex foo = {4,7}; ).

aluser 09-10-2004 03:31 PM

you can't do operator overloading in C; you'll have to write a function like struct complex add_complex(const struct complex *x, const struct complex *y)

afaik, the only way to assign all the members in a struct after it's initialized is to set it equal to another struct of the same type, e.g. foo = bar; I've found this annoying too.

drigz 09-10-2004 03:47 PM

i've just had to start compiling it with c++ so i can overload some of my functions, so i'm prepared to try and do it a c++ way - which way would require least new learning, since i know nothing about classes?

jim mcnamara 09-10-2004 03:50 PM

As an aside -

Looks like you're doing complex arithmetic.

C99 supports a large library of complex functions as well as the complex datatype. Most flavors of Linux support it.

drigz 09-10-2004 03:57 PM

Really? I figure it will be more educational (I will still need to know this for my exam...) and the theory writing a program will teach me it and also help me do homework quicker.

Mara 09-10-2004 04:07 PM

You don't have to deal with classes in C++. You can just use your code and add operator overriding.
Sidenote: I'd rather just use functions: add_complex() etc.

drigz 09-10-2004 04:22 PM

yeh but i've got some pretty complex functions for some of this stuff and id rather the shorter and more intuitve version. thanks tho.

drigz 09-11-2004 06:44 PM

Done it. Found a good guide here: http://www.cplusplus.com/doc/tutorial/tut4-2.html


All times are GMT -5. The time now is 01:18 AM.