【发布时间】:2013-01-19 23:54:26
【问题描述】:
所以我有一个看起来有点像这样的向量类(为了清楚起见,去掉了大多数方法):
class D3Vector {
private:
double _values[3];
public:
const double& operator[](const int index) const;
double& operator[](const int index);
};
double& D3Vector::operator[](const int index) {
assert(index >= 0 && index < 3);
return _values[index];
}
const double& D3Vector::operator[](const int index) const {
assert(index >= 0 && index < 3);
return _values[index];
}
在我的代码中,我将这个数组下标重载称为如下:
void func(D3Vector centre, double radius) {
double limits[6];
int i;
for (i = 0; i < 3; i++) {
// both these lines cause the error...
limits[i] = centre[i] - radius;
limits[i + 3] = centre[i] + radius;
}
...
}
但我在编译时收到此错误:
error: invalid types '<unresolved overloaded function type>[int]' for array subscript
现在,我摆弄了重载函数的签名,添加和删除引用符号,添加和删除 const,但我真的只是在这里猜测。
为像这样的实数向量类编写数组下标运算符重载的明智方法是什么,这样我们可以做一些简单的事情,例如:
instance[i] = 5.7;
和
new_value = instance[j] + 17.3;
?
EDIT:完整的类规范,根据要求:
class D3Vector {
private:
double _values[3];
public:
// constructors - no args inits to 0.0
D3Vector();
D3Vector(const double x, const double y, const double z);
// binary + and -:
D3Vector operator+(const D3Vector& right);
D3Vector operator-(const D3Vector& right);
// unary -, reverses sign of components:
D3Vector operator-();
// binary *, scales components.
D3Vector operator*(const double scale);
// the same, as self-assignment operations:
D3Vector& operator+=(const D3Vector& right);
D3Vector& operator-=(const D3Vector& right);
D3Vector& operator*=(const double scale);
// subscript operator, for member data access.
const double& operator[](const int index) const;
double& operator[](const int index);
// dot product:
double dot(D3Vector& right);
// cross product:
D3Vector cross(D3Vector& right);
// shortcut to vector length:
double mod();
// faster way of getting length squared:
double mod_squared();
};
【问题讨论】:
-
你有一个叫
centre的函数吗? -
您的代码看起来不错,但
<unresolved overloaded function type>看起来很可疑。你能发布一个完整的例子吗? -
按要求提供的完整类原型 :) -并且-哦,您的意思是函数而不是方法。不,没有代码可以看到的名为 center 的裸函数。
-
@tehwalrus,
limits也是? -
制作一个显示此错误的完整示例。您的代码中有错误,但它是您未显示的代码。在某个地方,您已经说服编译器
limits或centre是一个函数。