我们可以在 C++ 中类的成员函数中使用 cin>> 吗?



我正在尝试使用类似thiis 的成员函数初始化类矩阵

class mat{
int r,c;
float **p;

public:

mat(){}
mat(int,int);
void initialize();
};
mat :: mat (int r, int c){ //check for float and int if error occurs
p=new float*[r];
for(int i=0; i<r; ++i){
p[i]=new float(c);
}
void mat :: initialize(void){
int i,j;
cout<<"nEnter the elements : ";
for(i=0;i<r;++i){
for(j=0;j<c;++j){
cin>>p[i][j];
}
}
}
int main(){
mat m1(3,3);
cout<<"nInitialize M1";
m1.initialize();


return(0);
}

但当我编译并运行它并尝试初始化矩阵时,程序从未停止接收输入。有人能告诉我我做错了什么吗?

您需要像这样初始化rc

mat :: mat (int r, int c) :r(r), c(c){
p=new float*[r];
for(int i=0; i<r; ++i){
p[i]=new float[c];
}
}

别忘了添加析构函数。

最新更新