代码之家  ›  专栏  ›  技术社区  ›  Xalion

C++填充动态数组int

  •  0
  • Xalion  · 技术社区  · 8 年前

    我正在编写一个程序,将使用线程乘矩阵。我在填充动态整数数组时遇到问题 (无法使用向量) .

    Matrix::Matrix(int n, int m)
    {
        mac_ = new int[n * m];
    }
    
    Matrix::Matrix(std::istream & is)
    {
        int tmp;
        int i = 0;  
        is >> m_; //rows
        is >> n_; //columns
    
        Matrix(n_, m_); // using 1st constructor
    
        while (is.peek() != EOF) {
            is >> tmp;
            mac_[i] = tmp; // debug stop here
            i++;
        }
    }
    

    hpp文件的一部分:

    private:
        int n_; // columns
        int m_; // rows
        int *mac_;
    

    从调试中我得到:

    此0x0079f7b0{n_=3 m_=2 mac_=0x00000000{??}}

    我知道我会写作 mac_ = new int(n_*m_); 在第二个构造器中,但我想知道为什么第一个不工作。

    1 回复  |  直到 8 年前
        1
  •  2
  •   rocambille r233967    8 年前
    // ...
    
    Matrix(n_, m_); // using 1st constructor
    
    while (is.peek() != EOF) {
        is >> tmp;
        mac_[i] = tmp; // debug stop here
        i++;
    }
    

    看起来您认为在这里调用构造函数构造了实际的对象( this ),然后访问其成员属性 mac_ .

    事实上,像这样调用构造函数会创建一个与此矩阵无关的其他对象(因为您没有将其存储在变量中,所以它会在行尾被销毁)。

    因为你构建了另一个对象,而不是 , this->mac_ 未初始化,因此您的错误。

    如下修改代码:

    Matrix::Matrix(int n, int m)
    {
        init(n, m);
    }
    
    Matrix::Matrix(std::istream & is)
    {
        int tmp;
        int i = 0;  
        is >> m_; //rows
        is >> n_; //columns
    
        init(n_, m_);
    
        while (is.peek() != EOF) {
            is >> tmp;
            mac_[i] = tmp; // debug should not stop here anymore
            i++;
        }
    }
    
    void Matrix::init(int n, int m)
    {
        mac_ = new int[n * m];
    }
    

    注: 这里,我在函数中进行初始化 init (可能是私有方法)以避免代码重复。