0
我用指針傳遞做了一個C函數,只有指針不同時纔會給出正確的結果。例如:爲什麼我的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);
它只是把我一個星期來弄清楚爲什麼程序的最終輸出會發生變化。
爲了避免這種情況,聲明這種函數的最佳風格是什麼?我寫錯了嗎?
只發送一個'Point'參數,'pin',並使用其他無用的函數返回值作爲輸出結果。 – WhozCraig
你(假定)使用C++:不要像這樣的簡單例子通過指針傳遞對象。通過參考傳遞。 – Xirema