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

标签 c++ cin member-functions

我正在尝试使用像 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];
    }
}

并且不要忘记添加析构函数。

关于c++ - 我们可以在 C++ 类的成员函数中使用 cin>> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65362699/

相关文章:

c++ - 读取不同的输入类型 C++

c++ - 输出冗余

c++ - 将 ‘args’ 声明为引用数组错误

c++ - 模板函数无法将 'int' 转换为 nullptr_t

c++ - 在 SQL Server 表中进行更改时通知 C++ 应用程序

c++ - 如何使用可变参数模板制作通用的 Lua 函数包装器?

C++ 类枚举成员变量

C++:从堆栈内存返回 std::string 引用

c++ - 给定两个值时,输入循环循环两次

c++ - 每个 c++ 成员函数是否都隐含地将 `this` 作为输入?