我正在为向量和矩阵编写一个类,我想了解当我想重载 +、-、* 和 / 等常见运算符时如何避免开销和泄漏。
例如:
int main()
{
Vector3 aVector; //This has an address #1
Vector3 bVector; //This has another address #2
//rVector has an address #3
Vector3 rVector = aVector - bVector; //What will happen here?
}
和向量类:
class Vector3
{
public:
float vX, vY, vZ;
Vector3& operator-(const Vector3& vector3)
{
//I want to calculate this vector with the "vector3" param
//But then what do I return?
//Test 1:
Vector3 result; //This has an address #4
result.vX = vX - vector3.vX;
result.vY = vY - vector3.vY;
result.vZ = vZ - vector3.vZ;
return result; //Did I just overwrite address #3?
//Test 2:
vX = vX - vector3.vX;
vY = vY - vector3.vY;
vZ = vZ - vector3.vZ;
return (*this); //What happened to address #3? And I just changed this vector's values and I need then again later
}
}
最好的方法是什么?
编辑:还有一个问题,如果我想这样做:
Vector3 myVector = someVector - Vector3(x, y, z);
我如何对构造函数进行编码,使其不做任何事情……不好?我在想它会创建一个新类,但是在上面的句子中使用它之后我将无法引用它,这会导致以后出现问题吗?