gpt4 book ai didi

c++ - classList 数组不会向用户打印输出

转载 作者:行者123 更新时间:2023-11-30 01:46:20 25 4
gpt4 key购买 nike

所以这个程序的重点是询问学生他们的名字,他们这学期上了多少门课,然后它要求每门课的名字。我的问题是我无法让 classList 数组工作并在程序输出中将类名显示给用户。我已经标记了我认为问题的来源,我认为这是一个 super 简单的修复,但我只是没有看到它。帮忙?

顺便说一句,我正在 Microsoft Visual Studio 2013 中对此进行编码。

#include <iostream>
#include <string>

using namespace std;

class Student
{
public: //public class for the student
Student(string first_name, string last_name, int num, string list);
Student();


void input(); //input from the user
void output(); //output for the user depending on their input


// accessors
const string get_name();
const int get_numClasses();
const string get_classList();


// mutators
void set_name(string name);
void set_numClasses(int num);
void set_classList(string list);


private:
string name;
int numClasses;
string classList;
};


// constructor's variable
Student::Student()
{
name;
numClasses = 0;
classList;
}


// the accessors get called from the public class Student
string const Student::get_name()
{
return name;
}
int const Student::get_numClasses()
{
return numClasses;
}
string const Student::get_classList()
{
return classList;
}


// the mutators set for the public class Student
void Student::set_name(string studentName)
{
name = studentName;
}
void Student::set_numClasses(int num)
{
numClasses = num;
}
void Student::set_classList(string list)
{
classList = list;
}


// accessors here
void Student::input()
{
int x;

cout << "Enter your name (First name only): ";
cin >> name;
cin.ignore();
cout << "How many classes are you taking this semester?: ";
cin >> numClasses;
cin.ignore();

if (numClasses> 0)
{
string* classList = new std::string[numClasses]; // <--- THE ERROR IS ON THIS LINE I THINK
for (x = 0; x<numClasses; x++) // loop for the classList array
{
cout << "Enter name of class " << (x + 1) << endl;
cin >> classList[x]; // <--- OR MAYBE THE ERROR IS ON THIS LINE TOO?
}
}

cout << '\n' << endl;
}


// displays the output according to the user
void Student::output()
{
cout << "Students name: " << name << endl;
cout << "Number of classes this semester?: " << numClasses << endl;
cout << "Displayed Class List: " << classList << endl;
}

int main()
{
char go_again = 'Y';
while (go_again == 'y' || go_again == 'Y')
{
Student s1;
s1.input();

s1.output(); //output from the student

cout << "\nRestart with new data? (press y/n) " << endl;
cin >> go_again;
}


if (go_again == 'n')
{
return 0;
}

system("pause");
return 0;

}

最佳答案

您的Student 类声明了一个名为classListstring,但是您的input() 方法声明了一个新变量类型为string*,也被命名为classList。它被称为阴影,虽然合法,但要避免,因为正是您所看到的那种问题。这通常是无意的,而且几乎总是令人困惑。

关于c++ - classList 数组不会向用户打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33373101/

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