错误:非静态引用成员"std::ostream&Student::out",无法使用默认赋值运算符

error: non-static reference member 'std::ostream& Student::out', can't use default assignment operator

本文关键字:赋值运算符 默认 out 引用 静态 成员 std 错误 ostream Student      更新时间:2023-10-16

我是一个C++程序员的新手,在编写代码时遇到了以下错误:

C:UsersMattDesktopC++ ProjectsOperatorOverloadstudents.h|8|error: non-static reference member 'std::ostream& Student::out', can't use default assignment operator|

错误发生在这个头文件的第8行:

#ifndef STUDENTS_H 
#define STUDENTS_H
#include <string>
#include <vector>
#include <fstream>
class Student {
private:
std::string name;
int credits;
std::ostream& out;
public:
// Create a student with the indicated name, currently registered for
//   no courses and 0 credits
Student (std::string studentName);
// get basic info about this student
std::string getName() const;
int getCredits() const;
// Indicate that this student has registered for a course
// worth this number of credits
void addCredits (int numCredits);
void studentPrint(std::ostream& out) const;

};
inline
std::ostream& operator<< ( std::ostream& out, const Student& b)
{
b.studentPrint(out);
return out;
}
bool operator== ( Student n1, const Student&  n2)
{
if((n1.getCredits() == n2.getCredits())&&(n1.getName() == n2.getName()))
{
return true;
}
return false;
}
bool operator< (Student n1, const Student& n2)
{
if(n1.getCredits() < n2.getCredits()&&(n1.getName() < n2.getName()))
{
return true;
}
return false;
}
#endif

问题是,我不太确定这个错误意味着什么,也不知道如何修复它。有人有可能的解决方案吗?

代码的问题显然是类中的std::ostream&成员。从语义上讲,我怀疑拥有这个成员是否真的有意义。然而,让我们暂时假设你想保留它

  1. 任何用户定义的构造函数都需要显式初始化其成员初始值设定项列表中的引用。否则编译器将拒绝接受构造函数
  2. 编译器将无法创建赋值运算符,因为它不知道在赋值引用时应该发生什么

错误消息似乎与赋值运算符有关。您可以通过明确定义赋值运算符来解决这个问题,例如

Student& Student::operator= (Student const& other) {
// assign all members necessary here
return *this;
}

但是,更好的解决方案是删除引用参数。您可能根本不需要它:很少有类存储std::ostream&成员是有意义的。大多数时候,任何流都是一个短暂的实体,临时用于向其发送对象或从中接收对象。

在代码的某个地方,您正在对一个Student对象使用赋值运算符。但是您还没有专门定义赋值运算符,您只是在使用编译器生成的运算符。但是编译器生成的赋值运算符在具有引用成员时不起作用。禁用赋值运算符(通过将其设为私有运算符或将其删除),或者将ostream成员设为指针而不是引用。这一切都是假设你在你的类中真的需要这个ostream对象,我觉得这是可疑的。