在类函数调用期间丢失私有变量信息

losing private variable information during the class function calls

本文关键字:变量 信息 函数调用      更新时间:2023-10-16

下面的代码在运行时将显示私有成员变量(MaxRows,MaxCols)在调用函数输入时正在更改。你能帮忙吗?

如您所见,第一个构造函数生成私有变量的正确显示。 但是,该函数会将它们分开。

#include <iostream>
#include <string>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <windows.h>
#include <cstring>
#include <cctype>
#include <iomanip>
#include <algorithm>
#include <sstream>
using namespace std;
class TwoD
{
private:
    int MaxRows;
    int MaxCols;
    double** outerArray;
public:
    TwoD(int MaxRows, int MaxCols) 
    {
        outerArray = new double *[MaxRows];
        for (int i = 0; i < MaxRows; i++)
            outerArray[i] = new double[MaxCols];
            cout << MaxRows << MaxCols << endl;
    }
    void input()
    {
        cout << MaxRows << MaxCols << endl;
        for (int k = 0; k < MaxRows; k++)
        for (int j = 0; j < MaxCols; j++)
            cin >> outerArray[k][j];
    }
    void outPut()
    {
    for (int l = 0; l < MaxRows; l++)
    {
        for (int m = 0; m < MaxCols; m++)
            cout << outerArray[l][m] << " ";
        cout << endl;
    }
    }
    ~TwoD()
    {
    for (int i = 0; i < MaxRows; i++)
        delete[] outerArray[i];
    delete[] outerArray;
    }
};
int main()
{
TwoD example(5, 2);
example.input();
example.outPut();
return 0;
}

您从未实际将类成员设置为作为参数传递的值。

另外:您可能需要查看命名约定 - 通常使用maxRows而不是MaxRows

TwoD(int maxRows, int maxCols) : MaxRows(maxRows), MaxCols(maxCols)
    {
        outerArray = new ...

正确命名您的类成员将在这里对您有所帮助。重命名成员并在构造类时初始化它们。

令人困惑的是,您的参数与您的成员命名相同。

TwoD(int maxRows, int maxCols)
    : m_maxRows(maxRows)
    , m_maxCols(maxCol)