可能重复:
c ++警告:局部变量的地址
嗨,当我写这段代码时:
//Returns the transpose matrix of this one
SparseMatrix& SparseMatrix::transpose()const{
vector<Element> result;
size_t i;
for(i=0;i<_matrix.size();++i){
result.push_back(Element(_matrix.at(i)._col, _matrix.at(i)._row, _matrix.at(i)._val));
}
return SparseMatrix(numCol,numRow,result);
}
Run Code Online (Sandbox Code Playgroud)
我收到警告"返回地址或本地变量或临时".最后一行调用SparseMatrix构造函数.我不明白这段代码有什么问题,我怎么能修复它所以我可以按照自己的意愿返回一个SparseMatrix对象.
我正在写这个拷贝构造函数:
//CCtor of RegMatrix
RegMatrix::RegMatrix(const RegMatrix &other){
this-> numRow = other.getRow();
this-> numCol = other.getCol();
//Create
_matrix = createMatrix(other.numRow,other.numCol);
int i,j;
//Copy Matrix
for(i=0;i<numRow; ++i){
for(j=0;j<numCol; ++j){
_matrix[i][j] = other._matrix[i][j];
}
}
}
Run Code Online (Sandbox Code Playgroud)
在初始化列表中初始化numRow,numCol是否有问题,如下所示:numRow(other.numRow), numCol(other.numCol)
而不是:
this-> numRow = other.getRow();
this-> numCol = other.getCol();
Run Code Online (Sandbox Code Playgroud)
另外,我不知道是否存在这样的问题,是否存在在初始化列表中调用其他类的对象函数的问题,例如:
numRow(other.getRow())
Run Code Online (Sandbox Code Playgroud)
代替:
this-> numRow = other.getRow();
Run Code Online (Sandbox Code Playgroud) 我正在编写一个包含矩阵(具有双值)的类,表示为vector<vector<double>>;
我想实现operator=,用给定的稀疏矩阵的细节重新填充我的矩阵.我正在编写以下代码:
RegMatrix& RegMatrix::operator=(const SparseMatrix rhs){
if(*this != rhs){
_matrix.clear();
_matrix.resize(rhs.getRow());
int i;
for(i=0;i<rhs.getRow();++i){
_matrix.at(i).resize(rhs.getCol());
}
for(i=0;i<rhs.getSize();++i){
Element e = rhs.getElement(i);
_matrix[e._row][e._col] = e._val;
}
}
return *this;
}
Run Code Online (Sandbox Code Playgroud)
该resize()方法是否使用零自动填充向量?我的实施是否正常?
我写了这个方法来找到稀疏矩阵的次要:
SpMatrixVec SparseMatrix::minor(SpMatrixVec matrix, int col) const{
SpMatrixVec::iterator it = matrix.begin();
int currRow = it->getRow();
int currCol = col;
while(it != matrix.end()) {
if(it->getRow() == currRow || it->getCol() == currCol){
matrix.erase(it);
}
// if we have deleted an element in the array, it doesn't advance the
// iterator and size() will be decreased by one.
else{
it++;
}
}
// now, we alter the cells of the minor matrix to be of proper coordinates.
// this is necessary for sign …Run Code Online (Sandbox Code Playgroud)