wzsun
wzsun

Reputation: 425

Template Init-constructor error

Hey I'm having trouble figuring out how to get my template header to work. I have to get my init constructor to take in an array and reverse it. So for example if I have [1,2,3,4] it takes it in [4,3,2,1]

this is my template class:

#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;
    }

};

So yea if you could tell me what I'm doing wrong that'd be great.

Upvotes: 0

Views: 69

Answers (2)

Denis Ermolin
Denis Ermolin

Reputation: 5546

That's because when you pass array to function it converts to pointer. You must use DATA_TYPE as pointer:

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

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409356

It seems to me like you are declaring an instance of this class with int, like

Reverser<int> myVar;

Then the Data member will be of type int. In the constructor you then try to allocate memory (with new returning a int*) and assign it to the Data member, but you can't assign a pointer to a non-pointer.

So as you write in your comment, it should be

DATA_TYPE* Data;

Upvotes: 0

Related Questions