C++ 无法向获取向量的函数发送NULL
我有这个功能:C++ 无法向获取向量的函数发送NULL,c++,vector,C++,Vector,我有这个功能: void RegMatrix::MatrixInit(int numRow,int numCol, std::vector<double> fill) { do something; } 如何将NULL作为向量传递?您不能将NULL作为向量传递,您可以像这样传递空向量: MatrixInit( numRow, numCol, std::vector<double>() ) std::vector<doub
void RegMatrix::MatrixInit(int numRow,int numCol, std::vector<double> fill)
{
do something;
}
如何将NULL作为向量传递?您不能将NULL作为向量传递,您可以像这样传递空向量:
MatrixInit( numRow, numCol, std::vector<double>() )
std::vector<double> v;
MatrixInit(numRow, numCol, &v);
MatrixInit(numRow,numCol,std::vector())
请注意,最好将
填充
向量取为常量&
为了传递NULL
,您需要更改参数以接受向量*
指针,例如:
void RegMatrix::MatrixInit(int numRow, int numCol, std::vector<double> *fill)
{
if (fill != NULL)
{
do something with fill;
}
}
void RegMatrix::MatrixInit(int numRow、int numCol、std::vector*fill)
{
如果(填充!=NULL)
{
用填充物做某事;
}
}
当您需要传入向量时,您可以这样做:
MatrixInit( numRow, numCol, std::vector<double>() )
std::vector<double> v;
MatrixInit(numRow, numCol, &v);
std::vector v;
MatrixInit(numRow、numCol和v);
如果您想要一个表示特殊情况的值,可以创建一个静态变量并对其进行测试
static std::vector<double> null_fill;
void RegMatrix::MatrixInit(int numRow,int numCol, const std::vector<double> & fill = null_fill)
{
if (&fill == &null_fill)
// do something special
else
// do something;
}
static std::vector null\u fill;
void RegMatrix::MatrixInit(int numRow,int numCol,const std::vector&fill=null\u fill)
{
if(&fill==&null\u fill)
//做点特别的事
其他的
//做点什么;
}
您可以将参数类型设置为可选
顾名思义,这是一个可选参数。如果不使用参数,则传递
boost::none
。(不是NULL
;这是一个空指针常量,我们这里不使用指针)。NULL不是向量。当C++ java java语言的一个硬的世界,这里需要一个空的向量,那么你也应该明白,空指针不是Java中的空向量。在java中,你可以在java中发送空向量,实际上你也发送了一个向量指针。雷米-莱博- TeMB的答案是最像java的,但是K-Balo的答案C++更大,大概是说函数应该改变向量。没有参考,我假设fill是矩阵的初始值。如果是这样的话,那么它当然应该是&而不是const&。@wilhelmtell,因为原始值是通过值传递的,所以它不能更改向量。@Mark我大概是根据函数名说的。函数的签名意味着函数没有副作用,甚至没有返回值,我想这是一个错误。@wilhelmtell:它是一个非常量成员函数,可按以初始化对象。