错误:非静态引用成员"std::ostream&Student::out",无法使用默认赋值运算符
error: non-static reference member 'std::ostream& Student::out', can't use default assignment operator
我是一个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&
成员。从语义上讲,我怀疑拥有这个成员是否真的有意义。然而,让我们暂时假设你想保留它
- 任何用户定义的构造函数都需要显式初始化其成员初始值设定项列表中的引用。否则编译器将拒绝接受构造函数
- 编译器将无法创建赋值运算符,因为它不知道在赋值引用时应该发生什么
错误消息似乎与赋值运算符有关。您可以通过明确定义赋值运算符来解决这个问题,例如
Student& Student::operator= (Student const& other) {
// assign all members necessary here
return *this;
}
但是,更好的解决方案是删除引用参数。您可能根本不需要它:很少有类存储std::ostream&
成员是有意义的。大多数时候,任何流都是一个短暂的实体,临时用于向其发送对象或从中接收对象。
在代码的某个地方,您正在对一个Student
对象使用赋值运算符。但是您还没有专门定义赋值运算符,您只是在使用编译器生成的运算符。但是编译器生成的赋值运算符在具有引用成员时不起作用。禁用赋值运算符(通过将其设为私有运算符或将其删除),或者将ostream成员设为指针而不是引用。这一切都是假设你在你的类中真的需要这个ostream对象,我觉得这是可疑的。
相关文章:
- 默认赋值运算符如何在实际 STL 中实现
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- C++不同类型的默认赋值运算符
- 将默认赋值运算符声明为 constexpr:哪个编译器是正确的?
- 默认赋值运算符有权访问基类的私有成员
- 错误:非静态引用成员"std::ostream&Student::out",无法使用默认赋值运算符
- 默认的复制构造函数和复制赋值运算符给出奇怪的错误
- 在这种情况下,我们需要禁用默认的复制构造函数和赋值运算符
- 错误:非静态引用成员,无法使用默认赋值运算符
- 如果成员具有非平凡的noexcept赋值运算符,则默认的移动赋值不能显式为noexcept
- 外部C结构的C++默认复制/移动赋值运算符不是常量
- 如果类具有引用数据成员,为什么编译器不合成默认赋值运算符
- 模板赋值运算符不替换默认赋值运算符
- 删除默认C++复制和移动构造函数和赋值运算符的缺点
- 具有不同模板参数的模板类的默认赋值运算符
- 重载赋值运算符或使用默认运算符
- 为什么我不能在 C++ 中使用模板版本覆盖默认的复制构造函数和赋值运算符
- c++默认的复制和赋值运算符
- C++赋值运算符默认返回
- 当类成员是引用时,是否无法生成默认赋值运算符?(在C++中)