【发布时间】:2021-10-05 17:41:56
【问题描述】:
我有一个 Vector3 类,它的 + 和 * 运算符重载如下:
Vector3& operator+ (Vector3& v1, Vector3& v2)
{
Vector3 sum = Vector3(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
static Vector3& ref = sum;
return ref;
}
Vector3& operator* (Vector3& v1, double value)
{
Vector3 product = Vector3(v1.x * value, v1.y * value, v1.z * value);
static Vector3& ref = product;
return ref;
}
Vector3& operator* (double value, Vector3& v1)
{
Vector3 product = Vector3(v1.x * value, v1.y * value, v1.z * value);
static Vector3& ref = product;
return ref;
}
但是当计算 2 个向量 v1 和 v2 的线性组合时,我得到 2 个不同的结果,分别与一行进行:
#include <iostream>
#include "Vector3.h"
using namespace std;
int main()
{
Vector3 v1 = Vector3(1.0, 2.0, 3.0);
Vector3 v2 = Vector3(2, 2, 2);
Vector3 v3 = v1 * -1;
Vector3 v4 = v2 * 1.2;
cout << v3 + v4 << endl;
cout << (v1 * -1.0) + (v2 * 1.2) << endl;
return 0;
}
输出:
(1.4, 0.4, -0.6)
(-2, -4, -6)
【问题讨论】:
标签: c++ vector operator-overloading