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 { 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}; ). |
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. |
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?
|
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. |
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.
|
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. |
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.
|
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. |