您好,当警告“控制到达非无效函数的末尾”时,我该怎么办?
我的重载运算符有 try 和 catch 并且 returns *this ;
在 try 范围内。
我正在使用 Eclipse,G++ 是编译器,UBUNTU linux
NNmatrix & operator*=(const NNmatrix<T> &mtrxB)
{
// A=2*3 B=3*4 return C=2*4
const UINT aRows = this->size1();
const UINT aCols = this->size2();
const UINT bRows = mtrxB.size1();
const UINT bCols = mtrxB.size2();
try
{
// if cols of first(this) matrix == rows of second matrix
if (aCols != bRows) throw bad_alloc();
const UINT cRows = aRows;// = rows of first matrix
const UINT cCols = bCols; // = cols of second matrix
NNmatrix mtrxC(cRows, cCols);
T val;
for (UINT i = 0; i < cRows; i++)
{
for (UINT j = 0; j < cCols; j++)
{
val = 0;
for (UINT k = 0; k < bRows; k++)
{
val += this->matrix.at(i).at(k) * mtrxB.getElement(k, j);
}
mtrxC.setElement(i, j, val);
}
}
*this = mtrxC;
mtrxC.clear();
return *this;
}
catch (exception& e)
{
cout<<"Dimension don't match: ("<<aRows<<","<<aCols<<") ("<<bRows<<","<<bCols<<")"<<endl;
}
}
最佳答案
如果函数返回除 void
之外的任何内容,您需要确保所有代码路径都返回一个值。
如果您在该函数内部处理异常而不重新抛出,为什么不在函数末尾无条件地返回 return *this;
,而不是从 try
中返回阻止?
编辑:根据下面@Mark 的评论,简单地移动 return 语句会隐藏在所请求操作的上下文中的 fatal error ,并使库在该过程中相当不可靠。最好传播异常,如果这是您要处理就地乘法错误的方式(这似乎是一种合理的方法)。
关于c++ try and catch 时的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4247606/