我有一个基本的学生类(必须是一个类)(是的,没有封装,还有命名空间污染,请原谅),我想创建自定义提取和插入运算符。经过无数次的搜索,它仍然无法正常工作。我有的是这个
#ifndef student
#define student
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
string name;
double score;
Student();
Student(string name, double score) : name(name), score(score) {}
friend ostream& operator<<(ostream &out, Student &student);
friend istream& operator>>(istream &in, Student &student);
};
#endif
#include "student.h"
ostream& operator<<(ostream &out, Student &student)
{
out << student.name << ", " << student.score;
return out;
}
istream& operator>>(istream &in, Student &student)
{
if (!in >> name || !in >> score)
{
in.setstate(ios::failbit);
}
return in;
}
我已经尝试了很多事情,从 this->name 到 Student::name 到 name 到 Student::student.name 到更改实际上最终工作的函数签名,但它实际上并没有使运算符重载。请停下来:D
编辑:至于具体问题,它是在方法中访问 Student 类的成员。student.name 和 student.score 正在抛出一个
expected primary-expression before '.' token
而最下面的只是向其抛出不同解决方案的遗物,但它是范围错误。
编辑2:问题原来是与标题中的守卫发生冲突被称为学生因此预处理器会在任何地方使用“学生”这个词-_-感谢您的帮助