C ++方法签名问题

时间:2011-02-01 07:54:11

标签: c++ methods

我正在尝试调用下面的addValues:

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的正确签名是什么?

2 个答案:

答案 0 :(得分:1)

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

这个工作的原因是因为它是一个模板。由于您将值定义为数组,因此在编译时已知值Nvector<double> values[COUNT]。由于编译器在编译时知道值的大小,因此能够用N替换COUNT

由于它是一个模板,您可以使用任何大小的数组调用此函数,不一定是COUNT大小。

我还建议将新日期更改为参考,正如Fred Nurk建议的那样。

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

答案 1 :(得分: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值相同。

相关问题