如何更改以下代码以便我可以使用new
anddelete
而不是malloc
and free
?
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
class myclass{
private:
float **m_R;
public:
myclass();
~myclass();
float **getR(void);
void setR(void);
};
myclass::myclass()
{
// first allocate rows (for pointers)
m_R = (float**)malloc(3*sizeof(float));
// next allocate columns for float values
for(int i=0;i<3;i++)
*(m_R+i) = (float*)malloc(3*sizeof(float));
}
myclass::~myclass()
{
// first free memory allocated by columns
for(int i = 0; i < 3; i++)
{
free(m_R[i]);
}
// next free memory allocated by rows
free(m_R);
}
void myclass::setR(void)
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
m_R[i][j] = 10*i+j;
//cout << m_R[i][j] << ", ";
}
//cout << "\n";
}
}
float **myclass::getR(void)
{
return m_R;
}
int main () {
myclass obj;
obj.setR();
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
printf("%02d, ",(int)obj.getR()[i][j]);
}
cout << "\n";
}
return 0;
}
Edit1:请注意,我必须使用一个函数(不是我写的)float**
作为参数,我别无选择(例如vector
)而不是使用float**
.
Edit2:该功能来自Proximity Query Package(PQP),编写如下:
int
PQP_Distance(PQP_DistanceResult *result,
PQP_REAL R1[3][3], PQP_REAL T1[3], PQP_Model *o1,
PQP_REAL R2[3][3], PQP_REAL T2[3], PQP_Model *o2,
PQP_REAL rel_err, PQP_REAL abs_err,
int qsize = 2);