2011-02-01 88 views
2

我試圖撥打以下addValues:和C++方法簽名問題

Obj *s = new Obj(); 
vector<tm> dates(SIZE); 
vector<double> values[COUNT]; 
for (uint i = 0; i < COUNT; i++) { 
    values[i] = vector<double>(SIZE); 
} 
s->addValues(&dates, &values); // <- this is the error line 

我定義addValues:

void addValues(vector<tm> *newDates, vector<double> (*newValues)[COUNT]); 

確切的錯誤是:

no matching function for call to ‘Stock::addValues(std::vector<tm, std::allocator<tm> >*, std::vector<double, std::allocator<double> > (*)[5])’ 

我認爲這個想法是我的方法簽名不匹配。 addValues的正確簽名是什麼?

+0

不可複製:http://ideone.com/FEX9w – kennytm 2011-02-01 08:06:23

+0

除了`std :: vector`之外,你還使用了什麼其他`vector`? – 2011-02-01 08:12:02

回答

1
template <size_t N> 
void addValues(vector<tm>* newDates, vector<double> (&newValues)[N]); 

這個工作的原因是因爲它的模板。值N在編譯時已知,因爲您將值定義爲數組:vector<double> values[COUNT]。由於編譯器在編譯時知道值的大小,因此它可以用COUNT代替N

由於它是一個模板,您將能夠使用任何大小的數組調用此函數,而不一定是COUNT大小。

我還建議將newDates更改爲參考,正如Fred Nurk所建議的那樣。

template <size_t N> 
void addValues(vector<tm>& newDates, vector<double> (&newValues)[N]); 
1

這是我改寫了你的代碼,使其編譯:

#include <ctime> 
#include <vector> 

using namespace std; 

typedef unsigned int uint; 

#define SIZE 3 
#define COUNT 3 

struct Obj { 
    void addValues(vector<tm> *newDates, vector<double> (*newValues)[COUNT]) 
    {} 
}; 

int main() { 
    Obj *s = new Obj(); 
    vector<tm> dates(SIZE); 
    vector<double> values[COUNT]; 
    for (uint i = 0; i < COUNT; i++) { 
     values[i] = vector<double>(SIZE); 
    } 
    s->addValues(&dates, &values); 
} 

並正確編譯。

如您所見,代碼與您的代碼幾乎相同。嘗試檢查成員函數聲明中使用的COUNT值是否與您創建values時使用的COUNT值相同。