简体   繁体   English

从':: size_t'到'int'的转换需要缩小的转换

[英]conversion from '::size_t' to 'int' requires a narrowing conversion

I'm trying to implement a container class using the code given in the Chapter 18 of 'Programming Principles and Practices using C++'. 我正在尝试使用“使用C ++编程原理和实践”第18章中给出的代码来实现容器类。 And when I write the code for the initialization using initializer_list I get this error: 'conversion from '::size_t' to 'int' requires a narrowing conversion'. 当我使用initializer_list编写用于初始化的代码时,出现以下错误:“从':: size_t'到'int'的转换需要缩小转换”。

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>


class vector
{
public:
    vector(int s) 
        :sz{ s },
        elem{ new double[sz] }
    {
        for (int i = 0; i < sz; i++)
            elem[i] = 0.0;
    }

    vector(std::initializer_list<double>lst)
        :sz{ lst.size() }, elem{ new double[sz] }
    {                                  //compiler points to here for the error
        std::copy(lst.begin(), lst.end(), elem);
    }

    ~vector() { delete[] elem; }

    int size() const { return sz; }

    double get(int n) const { return elem[n]; }
    void set(int n, double d) { elem[n] = d; }
private:
    int sz;
    double* elem;
};

You're trying to convert a size_t into an int . 您正在尝试将size_t转换为int Assuming 32-bits, size_t can hold up to 2^32 because it's unsigned, whereas int can only hold 2^31 (because it can have negative values also). 假定为32位, size_t最多可以容纳2 ^ 32,因为它是无符号的,而int只能容纳2 ^ 31(因为它也可以具有负值)。

When you do this: 执行此操作时:

vector(std::initializer_list<double>lst)
    :sz{ lst.size() }

If lst.size() is greater than the value stored by an int , then the value can't properly be stored. 如果lst.size()大于int存储的值,则无法正确存储该值。 The solution would be to just use std::vector internally, and get rid of the sz member, but seeing as though it looks as if you're trying to make your own vector class, you should just make sz a size_t , since it better represents what you're trying to do. 解决方案是仅在内部使用std::vector并摆脱sz成员,但是如果看起来好像您正在尝试创建自己的vector类,则应该仅将szsize_t ,因为更好地代表您正在尝试做的事情。 After all, it's not as if your vector can have < 0 elements in it. 毕竟,这并不是说vector可以包含< 0元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM