将Vector与类一起使用时没有运算符错误
no operator error when used Vector with class
我创建了一个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";
}
相关文章:
- C++分数混合比较运算符错误
- 尝试将文件写入数组时运算符<<错误
- 我在C++中遇到插入运算符错误
- 可变长度数组 c++ & 没有运算符>>错误?
- ostream 运算符<<错误C++
- 运算符'=='错误
- 尝试从向量返回对象时出现"没有可行的重载运算符 [] 错误
- 字符串输入中没有匹配的错误运算符错误
- 唯一指针中的赋值运算符错误
- c++ 类型不提供调用运算符错误
- CIN 和 COUT 运算符错误C++
- C++ 未读取我的 % 运算符(错误:"运算符%"不匹配)
- { } 构造函数实现中的赋值运算符 => 错误
- C++重载运算符<错误
- C++ 矢量查找() 重载运算符 - 错误
- 重载的"运算符+"必须是一元或二进制运算符错误
- C++对象 [实现] 运算符 == 错误
- 无法在 Visual Studio 2013 中运行非常基本的代码 - 运算符">>"错误/生成错误
- 自制矢量模板运算符 [] 错误
- C++ 重载<<运算符错误