简体   繁体   English

处理C语言中vector3d(x,y,z)运算的最佳方法

[英]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. 现在,我希望能够以简单的方式在此t_vector之间进行操作。 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. 当然,我的必杀技是c ++中的一种“重载运算符”,但是我知道这在c中不存在。

So for you, what's the best way to deal with this kind of operation in c ? 那么对您来说,用c处理这种操作的最佳方法是什么?

C, unlike C++ is all about transparency. 与C ++不同,C完全是关于透明度的。 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. 但是,在C ++中,您可能会使add运算符采用常量对象。 You should probably do that in C as well. 您可能也应该在C中执行此操作。

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 ++样式的类运算符:

// 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. 当然,如果不需要this指针,也不需要它,则可以使用任何喜欢的命名方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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