1

我有一个基本的学生类(必须是一个类)(是的,没有封装,还有命名空间污染,请原谅),我想创建自定义提取和插入运算符。经过无数次的搜索,它仍然无法正常工作。我有的是这个

#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:问题原来是与标题中的守卫发生冲突被称为学生因此预处理器会在任何地方使用“学生”这个词-_-感谢您的帮助

4

2 回答 2

4

评论和长颈鹿船长的回答中指出了各种问题。另一个更关键的问题是:

您声明一个student在函数中调用的变量;#define但你的头球实际上student在头球后卫中!所以你的#defined 符号与你的变量名冲突,导致你看到的错误。标头保护的推荐语法类似于

#define STUDENT_H_INCLUDED
于 2016-02-08T20:43:42.507 回答
3

我看到你的一些问题>>

if (!in >> name || !in >> score)

!优先级高于 >>,使用 !(in >> student.name)

使用 student.name 和 student.score

就像您在之前的运算符中所做的那样。

对运算符的第二个参数使用 const 引用很有用<<。相应地更改朋友声明。

于 2016-02-08T20:41:15.570 回答