gpt4 book ai didi

c++ - 对象在另一个对象的变量内消失

转载 作者:行者123 更新时间:2023-12-02 06:42:47 24 4
gpt4 key购买 nike

我遇到了奇怪的程序行为并崩溃了。

我创建了“List”类,其中包含指向“Student”类对象的指针数组。我观察到我在“List”构造函数中成功调用了“Student”对象。但我无法从任何其他“列表”方法调用“学生”对象。

我什至检查了“List”构造函数和“push”方法内部测试的同一行,导致程序崩溃。

这是测试行:cout << (studentBox[numb] -> getRef()) << endl;

这是代码中有问题的部分:

#include <iostream>

using namespace std;

class Student
{
private:
int referenceNumb;
int markNumb;
public:
Student();
Student(int, int);
~Student();
int getRef();
int getMark();
};

class List
{
private:
int numb;
Student* studentBox[1000];
public:
List();
~List();
void push(int, int);
int getAVG();
};

int main()
{
List* base = NULL;
int x, y;
char mod;
do
{
cout << "Waiting for orders." << endl;
cout << "1 - Quit," << endl;
cout << "2 - Add new student," << endl;
cout << "3 - Calculate average mark," << endl;
cout << "0 - Create new list." << endl;
cin >> mod;

switch(mod)
{
case '0': base = new List(); break;
case '1': cout << "Bye."; break;
case '2':
if(base != NULL)
{
cout << "Specify student's reference number: "; cin >> x;
cout << "Specify student's mark: "; cin >> y;
base->push(x, y);
}
else cout << "List does not exist!" << endl;
break;
case '3':
if(base != NULL)
{
cout << "Average mark is equal: " << base->getAVG();
}
else cout << "List does not exist!";
cout << endl;
break;
default: cout << "Correct command required!" << endl; break;
}
}
while(mod!='1');
return 0;
}

Student::Student()
{
referenceNumb = NULL;
markNumb = NULL;
}

Student::Student(int r, int m)
{
referenceNumb = r;
markNumb = m;
}

Student::~Student()
{
referenceNumb = NULL;
markNumb = NULL;
cout << "pusto." << endl;
}

int Student::getRef()
{
return referenceNumb;
}

int Student::getMark()
{
return markNumb;
}

List::List()
{
int numb = 0;
studentBox[numb] = new Student();

cout << (studentBox[numb] -> getRef()) << endl;
}

List::~List()
{
}

void List::push(int x, int y)
{
cout << (studentBox[numb] -> getRef()) << endl;

if(studentBox[numb] != NULL)
{
studentBox[numb] = new Student();

cout << (studentBox[numb] -> getRef()) << endl;
}
else cout << "Hujnia" << endl;
}

int List::getAVG()
{
int temp = 0;
for(int i=0; i<numb; i++)
{
temp += studentBox[i]->getMark();
}

return (temp / numb);
}

最佳答案

我发现有几个主要问题。第一个是列表的 numb 成员未初始化。

List::List()
{
int numb = 0; // this creates a new local variable called numb, it doesn't
// initialize the numb member.
studentBox[numb] = new Student();

cout << (studentBox[numb] -> getRef()) << endl;
}

这样做:

List::List()
: numb(0) // initialize the numb member to zero.
{
studentBox[numb] = new Student();

cout << (studentBox[numb] -> getRef()) << endl;
}

另一个问题是 numb 似乎是用来指示列表的大小,但当添加新学生时它永远不会改变。

关于c++ - 对象在另一个对象的变量内消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13904884/

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