简体   繁体   中英

Best way to deal with vector3d (x,y,z) operation in c

I'm starting a project where i need to do operation between vector. It's a school project so i need to do everything by myself. I've this kind of structure.

typedef struct      s_vector
{
    float           x;
    float           y;
    float           z;
}                   t_vector;

Now, I want to be able to have operation between this t_vector in the simple way possible. My first (and only) idea that i have is to deal with function like this :

t_vector        *addv(t_vector *a, t_vector *b); // do a += b.

Of course my nirvana is a kind of "overloaded operator" like in c++, but I know this doesn't exist in c.

So for you, what's the best way to deal with this kind of operation in c ?

C, unlike C++ is all about transparency. You always know what is happening. As such overloading an operator to do the wrong thing is not supported and that kind of code is frowned upon. Thus you will have to create a named function to do what you want.

However, in C++ you would likely make the add operator take constant objects. You should probably do that in C as well.

As such I'd suggest:

t_vector t_vector_add(const t_vector *a, const t_vector *b);

In general I'd convert C++-style class operators as follows:

// C++
class Vector {
    public:
        Vector functionA(SomeType argument);
        Vector functionB(Vector argument)const;
        const Vector functionC(const Vector argument);
};

// C
t_vector *t_vector_functionA(t_vector *this, SomeType *argument);
t_vector *t_vector_functionB(const t_vector *this, t_vector *argument);
const t_vector *t_vector_functionC(t_vector *this, const t_vector argument);

Of course if you don't need the this pointer, don't require it, and you can use whatever naming scheme you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM