模板初始化构造函数错误

时间:2012-10-25 10:01:19

标签: c++ templates constructor

嘿,我无法弄清楚如何让我的模板标题工作。我必须让我的init构造函数接受一个数组并反转它。因此,例如,如果我有[1,2,3,4]则需要[4,3,2,1]

这是我的模板类:

#pragma once
#include <iostream>

using namespace std;

template<typename DATA_TYPE>
class Reverser
{
private:
    // Not sure to make this DATA_TYPE* or just DATA_TYPE
    DATA_TYPE Data;
public:
     // Init constructor
     Reverser(const DATA_TYPE& input, const int & size)
    {
        // This is where I'm getting my error saying it's a conversion error (int* = int), not sure
        // What to make Data then in the private section. 
        Data = new DATA_TYPE[size];
        for(int i=size-1; i>=0; i--)
            Data[(size-1)-i] = input[i];
    }

    DATA_TYPE GetReverse(){
        return Data;
    }

    ~Reverser(){
        delete[] Data;
    }

};

所以,如果你能告诉我我做错了什么,那就太好了。

2 个答案:

答案 0 :(得分:1)

那是因为当你将数组传递给函数时,它会转换为指针。您必须使用DATA_TYPE作为指针:

template<typename DATA_TYPE>
class Reverser
{
private:
    // Not sure to make this DATA_TYPE* or just DATA_TYPE
    DATA_TYPE* Data; //pointer
public:
     // Init constructor
     Reverser(const DATA_TYPE* input, const int & size) //pointer
    {
        // This is where I'm getting my error saying it's a conversion error (int* = int), not sure
        // What to make Data then in the private section. 
        Data = new DATA_TYPE[size];
        for(int i=size-1; i>=0; i--)
            Data[(size-1)-i] = input[i];
    }

    DATA_TYPE* GetReverse(){ //Returns Pointer
        return Data;
    }

    ~Reverser(){
        delete[] Data;
    }
};

答案 1 :(得分:0)

在我看来,您正在使用int声明此类的实例,例如

Reverser<int> myVar;

然后Data成员的类型为int。然后在构造函数中尝试分配内存(new返回int*)并将其分配给Data成员,但不能指定指向非指针的指针。

所以当你在评论中写下来时,它应该是

DATA_TYPE* Data;