从T转换为unsigned int,可能会丢失数据

时间:2019-04-07 01:57:33

标签: c++ templates dynamic-arrays

我正在尝试构建一个动态数组模板类,到目前为止,一切都进展顺利,直到我尝试使用double类型的新对象实例,它都会引发如下错误:

警告C4244“正在初始化”:从“ T”转换为“ unsigned int”,可能会丢失数据

错误C2108下标不是整数类型

我的问题挂在Vector(T aSize)函数中

ive环顾四周,我可以理解这些错误,但是尝试应用此修复程序似乎行不通,任何帮助都很棒。

#include "pch.h"
#include <iostream>
#include "Vector.h"

int main()
{
    std::cout << "Hello World!\n"; 

    Vector<int> test = Vector<int>(5);
    Vector<double> test2 = Vector<double>(10);

    test.insert(1, 8);
    test.insert(3, 22);
    test.getPosition(0);
    test.getSize();
    test.print();
    test[2] = 4;
    test[10] = 0;

    test.print();


    test2.insert(0, 50.0);

}
#include <iostream>
#include <string>

using namespace std;

template <class T>
class Vector
{
public:

    Vector();
    Vector(T aSize);
    ~Vector();
    int getSize();
    int getPosition(T position);
    void print() const;
    void insert(T position, T value);
    void resize(int newSize);
    int &operator[](int index);


private:
    T size;
    int vLength;
    T* data;
};

template <class T>
Vector<T>::Vector() 
{
    Vector::Vector(vLength);
}

template <class T>
Vector<T>::~Vector()
{
    delete[] data;
}

template <class T>
Vector<T>::Vector(T aSize)
{
    size = aSize;
    data = new T[size];
    for (T i = 0; i < size; i++)
    {
        data[i] = 0;
    }
}

template <class T>
void Vector<T>::print() const
{
    for (int i = 0; i < size; i++) 
    {
        cout << data[i] << endl;
    }
}

template <class T>
int Vector<T>::getPosition(T position)
{
    return data[position];
}

template <class T>
void Vector<T>::insert(T position, T value)
{
    data[position] = value;

    cout << "value: " << value << " was inserted into position: " << position << endl;
}
template <class T>
int Vector<T>::getSize()
{
    cout << "the array size is: " << size << endl;
    return size;
}

template <class T>
int &Vector<T>::Vector::operator[](int index)
{
    if ((index - 1) > size) {
        resize(index + 1);
    }
    return data[index];
}

template <class T>
void Vector<T>::resize(int newSize)
{
    T *temp;
    temp = new T[newSize];
    for (int i = 0; i < newSize; i++)
    {
        temp[i] = data[i];
    }

    delete[] data;
    data = temp;
    size = newSize;

    cout << "the array was resized to: " << newSize << endl;
}

1 个答案:

答案 0 :(得分:2)

您不应使用通用类型T来设置动态数组的大小。另外,您不应使用T遍历容器。您应该改用整数类型(intlong等)。