[英]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.我正在完成 BS 的“A Tour of C++”,并正在重新创建他在整个过程中使用的Vector
class,至少在前四章。
I hit a snag building the second version of the Vector
constructor with a std::initializer_list
.我在使用std::initializer_list
构建Vector
构造函数的第二个版本时遇到了障碍。 A static_cast<int>
is used to convert the size_type
to an int
so sz
of my Vector
can be initialized. static_cast<int>
用于将size_type
转换为int
,以便可以初始化Vector
的sz
。
But, for some reason, when I try to compile it on my personal machine and OnlineGDB, I get an error:但是,由于某种原因,当我尝试在我的个人机器和 OnlineGDB 上编译它时,我收到一个错误:
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*
?为什么要尝试将size_type
转换为double*
? Should it not simply be converting it to a regular int
?它不应该简单地将其转换为常规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
.在这里elem{lst.size()}
您正在使用size_t
初始化double*
。
And why do you do static_cast<int>( lst.size() )
?你为什么要这样做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.您的大小应与列表大小的类型相同,即size_t
,以避免出现负大小。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.