2012-10-25 43 views
0

嘿我无法弄清楚如何让我的模板头工作。我必须让我的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; 
    } 

};

所以如果你能告诉我我做错了什么,那会很棒。

回答

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

诶给我一个秒 – wzsun

+0

用法:INT * ARR =新INT [4]; Reverser r(arr,4); –

+0

好的,是的,我错误地启动它,但是当我试图检索使用GetReverse()的数据时,我认为它应该是一个int * result = new int [10]; result = reverseData.GetReverse();然而,我得到的转换错误int int * – wzsun

0

在我看来,像你这个声明类的一个实例与int,像

Reverser<int> myVar; 

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

所以,当你在你的评论写的,它应该是

DATA_TYPE* Data;