親愛的大家晚安
我有一個問題,看我在處理類,在很多情況下我使用向量的向量(二維向量),我的代碼運行得很好。但是,我有點困惑,查看我的頭檔案,我在受保護的變數中宣告了一個向量向量,然后在建構式部分的 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");
}
uj5u.com熱心網友回復:
在您的建構式中:
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_nRows和m_nCols變數一樣:
Matrix::Matrix(int rows, int cols)
: m_nRows(rows),
m_nCols(cols),
MATRIX(m_nRows, std::vector<double>(m_nCols, 0))
{
}
uj5u.com熱心網友回復:
您正在宣告MATRIX在建構式中命名的另一個變數。您必須改為在類中宣告resize()的MATRIX成員上使用。它的初始化 MATRIX可以是這樣的:
MATRIX.resize(m_nRows);
for (int i =0; i<m_nRows; i ){
MATRIX[i].resize(m_nCols, 0);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/373448.html
