简体   繁体   中英

static_cast<int> of std::initializer_list::size_type spits out “invalid conversion” error

I'm working through "A Tour of C++" by BS, and am recreating the Vector class that he uses throughout, at least the first four chapters.

I hit a snag building the second version of the Vector constructor with a std::initializer_list . A static_cast<int> is used to convert the size_type to an int so sz of my Vector can be initialized.

But, for some reason, when I try to compile it on my personal machine and OnlineGDB, I get an error:

main.cpp: In constructor 'Vector::Vector(std::initializer_list<double>)':
main.cpp:24:58: error: invalid conversion from ‘std::initializer_list::size_type {aka long unsigned int}’ to ‘double*’ [-fpermissive]
     :elem{lst.size()},  sz{static_cast<int>( lst.size() )}
                                                          ^

Why is it trying to convert the size_type to a double* ? Should it not simply be converting it to a regular int ?

Please see my attempt at a minimal reproducible example below.

#include <algorithm>
#include <initializer_list>

class Vector{
    double* elem;                             
    int sz;                                 
public:
    Vector(std::initializer_list<double> lst)
    :elem{lst.size()},  sz{static_cast<int>( lst.size() )}
    {
        std::copy(lst.begin(), lst.end(), elem);
    }
};

int main()
{
    Vector vec = {1.2, 1.3, 1.4};
    return 0;
}

Here elem{lst.size()} you are initializing a double* using a size_t .

And why do you do static_cast<int>( lst.size() ) ? Your size should be of the same type as the size of the list, which is size_t , to avoid negative sizes.

Here is your code after some editing:

#include <initializer_list>
#include <algorithm>
#include <iostream>

class Vector{
    size_t sz;
    double* elem;
public:
    Vector(std::initializer_list<double> lst)
            :sz{lst.size()},  elem{new double [sz]}
    {
        std::copy(lst.begin(), lst.end(), elem);
    }
    Vector(const Vector&) = delete ;
    Vector& operator=(const Vector &) = delete ;
    size_t size()const{
        return sz;
    }
    double& operator[](size_t i){
        return elem[i];
    }
    ~Vector(){ delete [] elem;}
};

int main()
{
    Vector vec={1.2,1.3,1.4};
    for(size_t i{}; i < vec.size(); ++i)
        std::cout << vec[i] << " ";
    return 0;
}

Live

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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