gpt4 book ai didi

c++ - 通过指针访问数组

转载 作者:行者123 更新时间:2023-11-28 01:26:51 25 4
gpt4 key购买 nike

我想通过 OOP 创建一个类似于类的数据库。在这个类中,有 3 个数组作为表中的列。我通过 insert() 函数 插入数据并通过 printEntries() 函数 打印数据。但是该函数无法访问数组来检索数据。

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;

class subject{

public:
int numOfStudents;
string subjectId;
int * marksArray;
int * indexArray;
char * gradeArray;
int index ; // index for inserting data

subject(int students , string subjectName){

numOfStudents = students;
subjectId = subjectName;
this->index =0 ;
//creating and pointing to arrays
int A[numOfStudents]; marksArray = A;
int B[numOfStudents]; indexArray = B;
char C[numOfStudents]; gradeArray = C;

}

void insert(int studentId , int mark , char grade){
indexArray[index] = studentId;
marksArray[index] = mark;
gradeArray[index] = grade;

this->index = this->index +1;
}

int getNumberOfEntries(){
return index ;
}

void printEntries(){
cout<< indexArray[0] << " O" << marksArray[0] << " " << gradeArray[0] << endl;
cout<< indexArray[1] << " OOO" << marksArray[1] << " " << gradeArray[1] << endl;
cout<< indexArray[2] << " OO" << marksArray[2] << " " << gradeArray[2] << endl;
}
};

int main(int argc, char const *argv[]){
subject S(10,"Mathematics");
cout<<S.subjectId<<endl;
cout<<S.numOfStudents<<endl;
S.insert(35,34,'A');
S.insert(33,34,'B');
S.insert(54,34,'C');
S.insert(21,34,'D');
S.insert(14,34,'F');
S.printEntries();
return 0;
}

输出是:

数学1035 O34 A0 OOO0

最佳答案

正如@paddy 在对您的问题的评论中所指出的,您的问题出在构造函数中。

//creating and pointing to arrays
int A[numOfStudents]; marksArray = A;
int B[numOfStudents]; indexArray = B;
char C[numOfStudents]; gradeArray = C;

您正在做的是保存第一个元素的地址,其余元素在您离开构造函数后消失。你很幸运,它甚至允许你保存第一个插入并引用评论你正在做的是“定义是未定义的行为”

std::vectors 替换指针并在其中插入元素一定会更容易。

class subject
{
public: // It's considered bad practive to have public data members in a class
std::vector<int> marksVector;
std::vector<int> indexVector;
std::vector<char> gradeVector;
// ...

void insert(int studentId , int mark , char grade){
indexVector.push_back(studentId);
marksVector.push_back(mark);
gradeVector.push_back(grade);

// No longer need to worry about index for next insert
}
};

关于c++ - 通过指针访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53386088/

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