使用ostream作为参考(C++)

use*_*562 11 c++ pass-by-reference ostream

我有一个家庭作业,头文件提供给我们,并且是不可更改的.我无法弄清楚如何正确使用"显示"功能,所以这里是相关的代码.

头文件:

#ifndef SET_
#define SET_

typedef int EType;

using namespace std;

#include <iostream>

class Set
{
  private:

    struct Node
    {
      EType Item;     // User data item
      Node * Succ;    // Link to the node's successor
    };

    unsigned Num;     // Number of user data items in the set
    Node * Head;      // Link to the head of the chain

  public:

    // Various functions performed on the set

    // Display the contents of the set
    //
    void display( ostream& ) const;

};

#endif
Run Code Online (Sandbox Code Playgroud)

这是我的"显示"功能的实现:

void Set::display( ostream& Out ) const
{
  Node * temp = Head;
  cout << "{ ";
  while( temp != NULL )
  {
  cout << temp << ", ";
  temp = temp->Succ;
  return Out;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的司机:

#include <iostream>
#include <iomanip>
#include "/user/cse232/Projects/project08.set.h"

using namespace std;

int main()
{
  Set X;
  X.insert(10);
  X.insert(20);
  X.insert(30);
  X.insert(40);
  X.display();
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误说在我的驱动程序中,我没有使用正确的参数.我理解这一点,因为.h文件使用ostream&作为参数.我的问题是,在将"display"作为一个好参数调用时,我在驱动程序文件中使用了什么?

ice*_*ime 11

如你所说,display期望一个类型的参数std::ostream &.

在您的显示方法实现中,您正在输出,std::cout其中违反接收输出流的逻辑作为方法的参数.这里,参数的要点是display调用者将能够提供他选择的输出流.如果他的选择恰好是标准输出,他会写:

x.display(std::cout);
Run Code Online (Sandbox Code Playgroud)

这意味着您的display实现应仅在Out参数中输出而不是std::cout.

另请注意:

  • 您的display实现返回一个值,它不应该void返回(返回类型)
  • std::为清楚起见,我在答案中使用了前缀,但在您的情况下不需要它们,因为头文件包含一个using namespace std;.