重建一个通过引用发送的变量
Rebulid a variable that sent by reference
这是我的代码
void SMatrix::pow(int power, SMatrix & result)
{
if (this->rowSize != this->colSize || this->rowSize != result.rowSize || this->colSize != result.colSize || power <= 0)
{
delete & result;
result = new SMatrix (result.rowSize, result.colSize);
}
}
在这种情况下,我试图删除此结果,并将其作为新结果发送 SMatrix
。我该怎么做? (reuslt = newM
.....向我询问 SMatrix *
,但它不适用于 &)。
大体上我可以这样构建它:
SMatrix * s = new SMatrix(4, 4);
要么
S矩阵 s(4, 4);
(指针与否)。
delete & result;
result = new SMatrix (result.rowSize, result.colSize);
您不能 delete
一个对象,然后对其调用 operator=
。您正在执行与此等效的操作:
std::string* j = new std::string ("hello");
delete j;
*j = "goodbye"; // Oops, there's no string whose value we can set
我想你可能只是想要 result = SMatrix (result.rowSize, result.colSize);
。您想要更改 result
的值,您不想删除或创建任何动态内容。
这段代码就是"doing it wrong"。
如果您有一个引用参数,则隐含的效果是指向它的任何指针的所有权都属于调用者。
void SMatrix::pow(int power, SMatrix & result)
{
if (this->rowSize != this->colSize || this->rowSize != result.rowSize || this->colSize != result.colSize || power <= 0)
{
delete & result;
result = new SMatrix (result.rowSize, result.colSize);
}
}
如果您的 SMatrix
没有合适的 operator=
,那么您应该有一个。换句话说,如果您这样做,应该会发生正确的事情:
if (rowSize != colSize || rowSize != result.rowSize || colSize != result.colSize || power <= 0)
{
result = SMatrix (result.rowSize, result.colSize);
}
(请注意,我删除了 delete
行和 new
运算符)
如果由于某种原因这不能正常工作,那么您需要修复它,而不是依赖于原始数据的分配方式。
这是我的代码
void SMatrix::pow(int power, SMatrix & result)
{
if (this->rowSize != this->colSize || this->rowSize != result.rowSize || this->colSize != result.colSize || power <= 0)
{
delete & result;
result = new SMatrix (result.rowSize, result.colSize);
}
}
在这种情况下,我试图删除此结果,并将其作为新结果发送 SMatrix
。我该怎么做? (reuslt = newM
.....向我询问 SMatrix *
,但它不适用于 &)。
大体上我可以这样构建它: SMatrix * s = new SMatrix(4, 4); 要么 S矩阵 s(4, 4); (指针与否)。
delete & result;
result = new SMatrix (result.rowSize, result.colSize);
您不能 delete
一个对象,然后对其调用 operator=
。您正在执行与此等效的操作:
std::string* j = new std::string ("hello");
delete j;
*j = "goodbye"; // Oops, there's no string whose value we can set
我想你可能只是想要 result = SMatrix (result.rowSize, result.colSize);
。您想要更改 result
的值,您不想删除或创建任何动态内容。
这段代码就是"doing it wrong"。
如果您有一个引用参数,则隐含的效果是指向它的任何指针的所有权都属于调用者。
void SMatrix::pow(int power, SMatrix & result)
{
if (this->rowSize != this->colSize || this->rowSize != result.rowSize || this->colSize != result.colSize || power <= 0)
{
delete & result;
result = new SMatrix (result.rowSize, result.colSize);
}
}
如果您的 SMatrix
没有合适的 operator=
,那么您应该有一个。换句话说,如果您这样做,应该会发生正确的事情:
if (rowSize != colSize || rowSize != result.rowSize || colSize != result.colSize || power <= 0)
{
result = SMatrix (result.rowSize, result.colSize);
}
(请注意,我删除了 delete
行和 new
运算符)
如果由于某种原因这不能正常工作,那么您需要修复它,而不是依赖于原始数据的分配方式。