因此,该计划的重点是询问学生的名字,本学期要参加多少个类(class),然后询问每个类(class)的名称。我的问题是我无法使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;

}

最佳答案

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

10-04 21:53
查看更多