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

问题描述 投票:2回答:1

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

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

错误C2108下标不是整数类型

我的问题在Vector(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;
}
c++ templates dynamic-arrays
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.