c++ - 为什么我的 C++ 函数必须有不同的指针参数?

标签 c++ pointers function-declaration

我制作了一个带有指针传递的 C 函数,它仅在指针不同时才给出正确的结果。例如:

void dotransform(Point *pout, const Point *pin, transform mat)
{
    pout->x = mat[0][0] * pin->x + mat[1][0] * pin->y + mat[2][0] * pin->z + mat[3][0] * 1.0;
    pout->y = mat[0][1] * pin->x + mat[1][1] * pin->y + mat[2][1] * pin->z + mat[3][1] * 1.0;
    pout->z = mat[0][2] * pin->x + mat[1][2] * pin->y + mat[2][2] * pin->z + mat[3][2] * 1.0;
}

dotransform() 应该这样调用:

//...
Transform toWorldMat;
Point local;
Point world;
dotransform(&world, &local, toWorldMat );

问题是,我团队中有人这样调用它:

Point p;
dotransform(&p, &p, toWorldMat);

我只花了一个星期的时间就弄明白了为什么程序的最终输出发生了变化。

为了避免这种情况,声明这种函数的最佳风格是什么?我这样写是不是错了?

最佳答案

鉴于您已经直接传递了 transform 对象(尽管不是通过 const&:您真的应该这样做),您有什么理由不能写代码如下:

Point dotransform(Point const& pin, transform const& mat)
{
    Point pout
    pout.x = mat[0][0] * pin.x + mat[1][0] * pin.y + mat[2][0] * pin.z + mat[3][0] * 1.0;
    pout.y = mat[0][1] * pin.x + mat[1][1] * pin.y + mat[2][1] * pin.z + mat[3][1] * 1.0;
    pout.z = mat[0][2] * pin.x + mat[1][2] * pin.y + mat[2][2] * pin.z + mat[3][2] * 1.0;
    return pout;
}

这将允许您编写如下代码:

Transform toWorldMat;
Point local;
Point world = dotransform(local, toWorldMat);

或者这个:

Point p;
p = dotransform(p, toWorldMat);

这些是编写此代码的正确、理想的 C++ 方法。

关于c++ - 为什么我的 C++ 函数必须有不同的指针参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40661256/

相关文章:

c - 将参数分配给局部变量时从不兼容的指针类型进行分配

c++ - 没有明显好处的功能声明

c - void(*) void 和 int(*) int 在 C 中是什么意思?

c++ - 使用std::forward与RefRefCast的完美转发

c++ - 如何编写 MultiPart 下载 C++ 程序

c++ - 如何检查 std::max_element 是否返回了一个元素?

javascript - 原型(prototype)中的函数声明 "pollute"是原型(prototype)吗?

c++ - 解析 C 头文件

c - 指向函数错误的指针

c++ - C 中指向 char 的指针的默认值