因此,该计划的目的是向学生询问他们的名字,他们在本学期学习了多少课程,然后询问这些课程的名称。我的问题是我无法使classList
数组工作,并在程序输出中将类名显示回用户。我已经标记了我认为该问题的来源,我认为这是一个非常简单的解决方案,但我只是没有看到它。帮助
我顺便在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;
}
答案 0 :(得分:3)
您的Student
类声明名为string
的{{1}},但您的classList
方法声明了一个类型为input()
的新变量,也称为string*
}。它被称为阴影,并且,虽然合法,但要避免,因为您正在看到的问题。它通常是无意识的,几乎总是令人困惑。
答案 1 :(得分:1)
您有一个名为classList
的类成员std::string
。
但是,您还在classList
函数中声明了不同的input
:string* classList = new std::string[numClasses];
这不会修改classList
类数据成员。它是一个局部变量,它隐藏了类数据成员。
您可以将每个类名附加到类数据成员并避免使用该数组。
// string* classList = new std::string[numClasses];
std::string className;
for (x = 0; x<numClasses; x++) // loop for the classList array
{
cout << "Enter name of class " << (x + 1) << endl;
//cin >> classList[x];
cin >> className;
classList += className + " ";
}