gpt4 book ai didi

来自类的c++第二个函数无法访问第一个

转载 作者:行者123 更新时间:2023-11-30 05:28:06 27 4
gpt4 key购买 nike

我的代码将整数存储在 [n] x [n] 矩阵中。但是当我使用我的 printMatrix() 方法时,它在命令提示符下只返回零,而不是我之前分配给矩阵的整数。我想我必须使用引用/指针,但我不太确定如何使用。这是我的代码:

#include <iostream>
#include <vector>

using namespace std;

class Matrices
{
public:
Matrices();
void storeMatrix(vector <vector <int> > matr, int n);
void printMatrix(vector <vector <int> > matr, int n);

private:
int n;
vector <vector <int> > matr;
int cell;
};//class Matrices
Matrices::Matrices()
{

}//Constructor

void Matrices::storeMatrix(vector <vector <int> > matr, int n)
{
for( int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cout << "Please insert an int for matr [" << i << "] [" << j << "]" << endl;
cin >> cell;
matr[i][j] = cell;
}
}


}//storeMatrix

void Matrices::printMatrix(vector <vector <int> > matr, int n)
{
for( int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cout << matr[i][j];
}
cout<<endl;
}
}//printMatrix


int main()
{
int m;
cin >> m;
int n = 1;

for (int i = 1; i <= m; i++) // loop to make the input integer equivalent to power of 2;
n = n * 2;

vector <vector <int> > matr (n , vector <int> (n));
Matrices k;
k.storeMatrix(matr, n);
k.printMatrix(matr, n);


return 0;
}

有什么办法解决吗?

最佳答案

删除与printMatrix()相关的所有参数.在 main() 及其原型(prototype)(在类内)及其定义中 void YourClassName::printMatrix() .然后在其定义中设置:

cout << this->matr[i][j];//请参阅下面的进一步说明

而不是这个:

cout << matr[i][j];

添加This将打印您已在上一个函数中填充数据的“当前实例”的私有(private)成员。

也在你的store()您需要“链接”您正在对当前实例执行的操作。

总体:此设计应该可以帮助您更好地理解正在发生的事情。看这个 main():

int main()
{
int m;
int n = 1;

cin >> m;

Matrices k(m, n); // create an object k
k.storeMatrix(); // store matrix for "this" object k
k.printMatrix(); // print matrix of "this" object k

return 0;
}

然后看看类:

class Matrices
{
public:
Matrices();
Matrices(int, int);
void storeMatrix();
void printMatrix();

private:
int n;
vector <vector <int> > matr;
int cell;
};//class Matrices

Matrices::Matrices()
{}

Matrices::Matrices(int m, int n)
{
for (int i = 1; i <= m; i++) // loop to make the input integer equivalent to power of 2;
n = n * 2;

vector <vector <int> > _matr (n, vector <int>(n));
this->matr = _matr;

}//Constructor

void Matrices::storeMatrix()
{
for (int i = 0; i < this->matr.size(); i++)
{
for (int j = 0; j < this->matr[i].size(); j++)
{
cout << "Please insert an int for matr [" << i << "] [" << j << "]" << endl;
cin >> cell;
this->matr[i][j] = cell; //whatever "this" object is, store its matrix
}
}
}//storeMatrix

void Matrices::printMatrix()
{
for (int i = 0; i < this->matr.size(); i++)
{
for (int j = 0; j < this->matr[i].size(); j++)
{
cout << this->matr[i][j]; // whatever "this" objecct is, print its matrix
}
cout << endl;
}
}//printMatrix

关于来自类的c++第二个函数无法访问第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36957206/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com