class、C++ 中矢量的双重声明和初始化?

Double declaration and initialization of vector in a class, C++?

晚安亲爱的

我有一个问题,请看我使用 类 并且在许多情况下我使用向量的向量(2D 向量),我的代码运行得很好。然而,我有点困惑,看看我的头文件,我在我的受保护变量中声明了一个向量的向量,然后在我的构造函数部分的 cpp 文件中我再次声明了向量的向量,但是这次给出了所需的大小并具有所有元素中的“0”。但是,当我尝试在我的成员函数中使用这个向量的向量时,似乎没有维度被删除而不是“0”值,如果我使用 .size() 输出是“0”,我期待 3。

但是,当我再次声明成员中向量的向量(参见 cpp 文件中的注释行)函数时,代码给出了 3 和由“0”组成的 3 X 3 的完整矩阵。

这是为什么?使用构造函数基本上就是给变量赋值。

查看下一个代码,cpp 文件上的注释行是我再次声明矢量的地方。

头文件是:

#pragma once
#include <iostream>
#include <vector>

class Matrix
{
private:
    const int m_nRows;
    const int m_nCols;
protected:
    std::vector <std::vector <double>> MATRIX;

public:
    Matrix(int rows, int cols);
    ~Matrix();
    void getMatrix();
};

cpp 文件是:

#include "Matrix.h"

Matrix::Matrix(int rows, int cols)
    : m_nRows(rows),
    m_nCols(cols)
{
    std::vector <std::vector <double>> MATRIX(m_nRows, std::vector<double>(m_nCols, 0));
}

Matrix::~Matrix()
{
}

void Matrix::getMatrix()
{
    //std::vector <std::vector <double>> MATRIX(m_nRows, std::vector<double>(m_nCols, 0));
    std::cout << MATRIX.size() << std::endl;
    for (auto& columns : MATRIX)
    {
        for (auto& element : columns)
        {
            std::cout << element << " ";
        }
        std::cout << "\n";
    }

}

主文件是:

#include <iostream>
#include <vector>
#include "Matrix.h"

    int main() {
        int rows = 3;
        int cols = 3;
    
        Matrix SmallMatrix(rows, cols);
        SmallMatrix.getMatrix();
    
        system("pause>0");
    }

您正在构造函数中声明另一个名为 MATRIX 的变量。您必须改为在 class 中声明的 MATRIX 成员上使用 resize()。那个MATRIX的初始化可以是这样的:

MATRIX.resize(m_nRows);
for (int i =0; i<m_nRows; i++){
   MATRIX[i].resize(m_nCols, 0);
}

在你的构造函数中:

Matrix::Matrix(int rows, int cols)
    : m_nRows(rows),
    m_nCols(cols)
{
    std::vector <std::vector <double>> MATRIX(m_nRows, std::vector<double>(m_nCols, 0));
}

你定义了一个全新的变量,名称为MATRIX,与成员变量Matrix::MATRIX.

完全不同

要初始化 Matrix::MATRIX 成员变量,您应该在成员初始化列表中进行,就像 m_nRowsm_nCols 变量一样:

Matrix::Matrix(int rows, int cols)
    : m_nRows(rows),
    m_nCols(cols),
    MATRIX(m_nRows, std::vector<double>(m_nCols, 0))
{
}