我有一个类,它本质上是一个带有标签内容的数组,我想为它定义一些运算符。我想以这样一种方式来改变类中元素的数量很容易,因为我希望 future 的用户会改变跟踪的变量,但我也想确保类上的基本算术运算是尽可能高效。
我可以看到两种实现运算符的方法。以 Vector2D
为例类:
struct Vector2D {
//members
const static int nElem = 2;
double x;
double y;
//Constructors
Vector2D() {}
Vector2D(double X, double Y) : x(X), y(Y) {}
//Operators
double& operator[] (int index) {
switch(index) {
case 0:
return x;
case 1:
return y;
default:
return std::out_of_range ("Oops");
}
}
// Option 1: operator+ by constructing result
Vector2D operator+ (const Vector2D & rhs) const {
return Vector2D(x + rhs.x, y+rhs.y);
}
// Option 2: operator+ using loop and [] operator
Vector2D operator+ (const Vector2D & rhs) const {
Vector2D result;
for(int i = 0; i < nElem; i++)
result[i] = (*this)[i] + rhs[i];
return result;
}
};
假设我使用-03 优化,operator+
的两个实现之间会有什么区别吗? ?我的理解是,由于默认 Vector2D
构造函数没有代码体并且类内容是默认数据类型,选项 2 中调用默认构造函数没有额外开销 result
在设置其成员之前。我希望这两者是等价的,但我对我的知识没有足够的信心来确定。
最佳答案
你的方法根本行不通。如果您希望某人能够更改 nElem
,则不能使用 x
、y
作为您的名字。为什么?因为将 nElem
更改为 3 不会神奇地添加 z
。由于您不能在 x
和 y
上执行 for
循环,因此您对 nElem
的定义是没有意义的。
最后,这是一个数字模板使用的教科书案例。创建一个 vector ,根据它有多少元素进行模板化。
做这样的事情:
template<unsigned int LEN>
class Vector{
double v[LEN];
public:
Vector operator+(const Vector &o){
Vector res;
for (unsigned int i=0;i<LEN;++i) // with -O3 and small LEN this will be unrolled
res.v[i]=v[i]+o.v[i];
}
// ... etc.
};
然后你像这样使用它:
Vector<2> my_2d_vec;
Vector<3> my_3d_vec;
关于c++ - 在运算符中构造结果与在默认构造的对象上操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17822114/