![](/img/trans.png)
[英]error: non-static reference member - can't use default assignment operator
[英]error: non-static reference member 'std::ostream& Student::out', can't use default assignment operator
我是一位C ++新手,在编写代码时遇到了以下错误:
C:\Users\Matt\Desktop\C++ Projects\OperatorOverload\students.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对象,我对此感到怀疑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.