在下面的简化代码中,我有一个具有两个属性的类,我需要根据另一个的值更改一个而不更改第二个的值。我不想创建一个新的临时变量来做它(我不想分配新内存并清除旧内存),我需要使用指针
#include<iostream>
using namespace std;
class A{
private:
int **m1;
int **m2;
void allocate_mem(int ***ptr){
*ptr = new int*[1];
(*ptr)[0] = new int[1];
}
public:
A(){
allocate_mem(&m1);
m1[0][0] = 1;
allocate_mem(&m2);
m2[0][0] = 1;
}
//I need a method that change m2 (according to the value of m2) without changhig the value of m2
//this following doesn't work
A renew(){
if(m1[0][0]>0)
m2[0][0] = 1000;
}
~A(){
delete[] m1[0];
delete[] m1;
delete[] m2[0];
delete[] m2;
}
void create_output(){
cout << m1[0][0] << endl << m2[0][0] << endl;
}
};
答案 0 :(得分:0)
将A renew()
更改为void renew()
,代码可以正常运行。
#include<iostream>
using namespace std;
class A{
private:
int **m1;
int **m2;
void allocate_mem(int ***ptr){
*ptr = new int*[1];
(*ptr)[0] = new int[1];
}
public:
A(){
allocate_mem(&m1);
m1[0][0] = 1;
allocate_mem(&m2);
m2[0][0] = 1;
}
//I need a method that change m2 (according to the value of m1) without changhig the value of m1
void renew(){
if(m1[0][0]>0)
m2[0][0] = 1000;
}
~A(){
delete[] m1[0];
delete[] m1;
delete[] m2[0];
delete[] m2;
}
void create_output(){
cout << m1[0][0] << endl << m2[0][0] << endl;
}
};
int main(){
A mat;
mat.create_output();
mat.renew();
mat.create_output();
return 0;
}
这会产生:
1
1
1
1000