我写了这样一个类:
class vector3D{
public:
double x,y,z;
}
我重载 + 运算符:
class vector3D{
public:
double x,y,z;
vector3D operator+(const vector3D &lhs)
{
vector3D temp(x+lhs.x,y+lhs.y,z+lhs.z);
return temp;
}
}
但是使用C=A+B
比
C.x = A.x + B.x;
C.y = A.y + B.y;
C.z = A.z + B.z;
我认为这是因为在 + 重载函数中定义了一个 vector3D 实例。无论如何要避免这种情况?
(仅供引用:我使用此标志构建:-Wall -Wextra -Wunreachable-code -m32 -DNDEBUG -O2 -D_LARGEFILE64_SOURCE -D_REETRANT -D_THREAD_SAFE
)
编辑: 这就是我测试两种方法速度的方式(在 main() 中):
//test bench
vector3D A(0.0,0.0,0.0), B(1e-9,1e-9,1e-9);
clock_t c = clock();
//case A
for(long int i=0;i<1000000000;i++)
{
A = A + B;
}
cout<<"case A took: "<<1.0*(clock()-c)/CLOCKS_PER_SEC<<A<<endl;
c = clock();
//case B
for(long int i=0;i<1000000000;i++)
{
A._x = A._x+B._x;
A._y = A._x+B._y;
A._z = A._x+B._z;
}
cout<<"case B took: "<<1.0*(clock()-c)/CLOCKS_PER_SEC<<A<<endl;
结果是:
case A took: 5.539[1, 1, 1]
case B took: 1.531[2, 2, 2]
最佳答案
由于您要创建一个额外的对象,它会带来一些开销。这是固有的。
但是,查看您想要的“有效载荷行”,它们与您在 operator+=
主体中添加一些 other
非常相似:
vector3D &operator+=(const vector3D &other) // Note - no objects created.
{
x += other.x;
y += other.y;
z += other.z;
return *this; // Note - return by reference.
}
当然,operator+=
修改了它的左操作数(这正是您拥有 operator+
及其对象创建开销的原因)。
一般来说,对于适用的重物,您应该更喜欢 operator+=
(另请参阅 this question)。
关于c++以有效的方式重载加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31223320/