簡體   English   中英

錯誤:非靜態引用成員'std :: ostream&Student :: out',不能使用默認賦值運算符

[英]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&成員。 從語義上講,我懷疑擁有此成員是否真的有意義。 但是,讓我們暫時假設您想要保留它。 有一些含義:

  1. 任何用戶定義的構造函數都需要在其成員初始化程序列表中顯式初始化引用。 否則,編譯器將拒絕接受構造函數。
  2. 編譯器將無法創建賦值運算符,因為它不知道在分配引用時應該發生什么。

該錯誤消息似乎與賦值運算符有關。 您可以通過顯式定義賦值運算符來解決此問題,例如

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM