2013-01-19 25 views
3

所以我有一個載體類,看起來有點像這樣(大多數方法剝離出來的清晰度):懸而未決的重載函數類型 - 數組下標重載在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 

現在,我已經弄清楚重載函數的簽名,添加和刪除引用符號,添加和刪除常量,但我真的只是猜測在這裏。

什麼是寫了一個向量類的實數,這樣使我們能夠做簡單的事情,如數組下標運算符重載是明智的:

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(); 
}; 
+0

你有一個叫做'centre'的函數嗎? – chris

+0

你的代碼看起來很好,但是''看起來很腥。你能發佈一個完整的例子嗎? – Philipp

+0

按照要求的全班原型:) - 並且 - 哦,你的意思是一種功能而不是一種方法。不,沒有代碼可以看到的稱爲中心的裸函數。 – tehwalrus

回答

7

正如評論者指出,這個錯誤,當您試圖打電話與支架[]而不是括號()功能彈出。這正是這裏發生的事情,並不是很明顯,因爲我簡化了代碼示例。

在的問題,我張貼和示例函數調用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> CON檢索它們TAINER。這很複雜,因爲我(成功)在同一行使用了我真正的數組下標重載類,這讓我很困惑!該文件上的編譯器錯誤「列號」事實上指向之後的第一個字符,進一步混淆了水域。

非常感謝所有評論過的人。