将Vector与类一起使用时没有运算符错误

no operator error when used Vector with class

本文关键字:运算符 错误 Vector 一起      更新时间:2023-10-16

我创建了一个for循环来打印输入的学生信息,但当我使用cout << st.printInfo() << endl;打印出来时,我得到了no operator "<<" matches these operants

学生班级:

class Student {
private:
    string nameSurname;
    int score;
public:
    void printInfo();
    void setName(string _nameSurname) { nameSurname = _nameSurname; }
    void setScore(int _score) { score = _score; }
    Student() {
        nameSurname = "Not Entered";
        score = 0;
    }
    ~Student() {}
};

打印功能:

void Student::printInfo()
{
    cout << "-----------------" << endl;
    cout << "Name and Surname : " << nameSurname << endl;
    cout << "Score : " << score << endl;
    cout << "-----------------" << endl;
}

主要功能:

vector<Student> v;
    string nameSurname;
    int score;
    Student st;
for (int i = 0; i < v.size() + 1; i++)
        {
            cout << "Enter " << i + 1 << " Student Name and Surname : " << endl;
            cin.ignore();
            getline(cin, nameSurname);
            st.setName(nameSurname);
            cout << "Enter Student's Score : " << endl;
            cin >> score;
            st.setScore(score);
            v.push_back(st);
        }

下面的循环部分内部显示了错误。for循环也在主函数中。

for (int i = 0; i < v.size(); i++)
    {
        cout << st.printInfo() << endl;
    }

printInfo函数返回void,而std::ostream没有打印void的功能。

更改printInfo以返回值
或者单独调用printInfo函数
或者将std::ostream传递给printInfo函数。

最好的方法是在Student类中重载operator<<

编辑1:详细信息:
您的for循环应该是:

for (int i = 0; i < v.size(); i++)
{
    v[i].printInfo();
    cout << "n";
}