[英]unresolved overloaded function type — array subscript overloading in C++
所以我有一個看起來有點像這樣的矢量類(大多數方法為了清晰起見而被剝離):
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;
?
編輯 :完整的類規范,根據要求:
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();
};
正如評論者指出的那樣,當您嘗試使用方括號[]
而不是括號()
調用函數時,會彈出此錯誤。 這正是這里發生的事情,並不是很明顯,因為我簡化了代碼示例。
在這個問題中,我發布了一個名為func
示例函數 - 這實際上是一個繼承類的構造函數(因此,而不是發布所有代碼,我簡化了。)
基類包含我們需要知道的所有內容:
class D3Shape {
protected:
double l[6];
virtual void initilise_limits() = 0;
public:
virtual bool contains(D3Vector point) = 0;
vector<double> limits();
};
即我混淆了l
,私有成員變量存儲了我正在尋找的double[6]
,帶有limits()
,一個用於在std::vector<double>
容器中檢索它們的函數。 這是因為我(成功)在同一行上使用我的實際數組下標重載類這一事實使我感到困惑! 文件上的編譯器錯誤“列號”實際上指向=
之后的第一個字符,進一步混淆了水域。
非常感謝所有評論的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.