我正在使用DirectXMath.h,其中所有乘法和操作都是使用XMVECTOR(SIMD包装器)完成的,而存储使用XMFLOAT3,其中包含3个浮点数。但是在这段特定的代码中我真的需要添加一个 *运算符适用于XMFLOAT3(适用于XMFLOAT3 * XMFLOAT3和XMFLOAT3 *浮动)。我可以这样做吗?或者我必须篡改SDK中的DirectXMath头文件吗?
答案 0 :(得分:4)
是的,您可以定义您的重载,但仅作为免费功能,而不是成员功能。
所以你可以做这样的事情(假设这是你感兴趣的超载):
XMFLOAT3 operator*(XMFLOAT3 a, XMFLOAT3 b) {
// whatever
}
答案 1 :(得分:3)
当然,在C ++中,您可以将运算符重载作为自由函数提供,如下所示:
XMFLOAT3 operator*(XMFLOAT3 left, XMFLOAT3 right)
{
...
}
如果在性能敏感的代码中使用它,请检查pass-by-value和pass-by-const引用是否会对发出的代码/性能产生任何影响。
答案 2 :(得分:3)
XMFLOAT3 operator*(const XMFLOAT3& a, const XMFLOAT3& b){
XMFLOAT3 ans;
...
return ans;
}
请注意,这会返回答案的副本,而不会修改任何2个操作数。这适用于*
运算符的语义。
答案 3 :(得分:2)
向前走,只需定义operator*
:
XMFLOAT3 operator*(XMFLOAT3 l, XMFLOAT3 r) {
XMVECTOR lvec(XMLoadFloat3(&l));
XMVECTOR rvec(XMLoadFloat3(&r));
//Perform operations
}
XMFLOAT3 operator*(XMFLOAT3 l, float r) {
XMVECTOR lvec(XMLoadFloat3(&l));
//Perform operations
}
XMFLOAT3 operator*(float l, XMFLOAT3 r) {
XMVECTOR rvec(XMLoadFloat3(&r));
//Perform operations
}