从 T 转换为无符号 int,可能会丢失数据

Conversion from T to unsigned int, possible loss of data

本文关键字:数据 转换 无符号 int      更新时间:2023-10-16

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

警告 C4244"正在初始化":从"T"转换为"无符号 int",可能会丢失数据

错误 C2108 下标不是整数类型

我的问题挂在矢量(T aSize(函数中

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

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

不应使用泛型类型T来设置动态数组的大小。此外,您不应使用 T 循环遍历容器。你应该改用整型(intlong等(。