微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用ostream作为参考(C)

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

文件

#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

这是我的功能实现“显示”:

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

这是我的司机:

#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();
}

我收到的错误说,在我的驱动程序中,我没有使用正确的参数.我明白这一点,因为.h文件使用ostream&作为参数.我的问题是,在调用显示”作为一个很好的参数时,我在驱动程序文件中使用什么?

解决方法

正如你所说,显示器需要一个类型为std :: ostream& amp;

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

x.display(std::cout);

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

另请注意:

>你的显示实现返回一个值,它不应该(void return type)>为了清楚起见,我在我的答案中使用std ::前缀,但是在你的情况下它们不是必需的,因为头文件包含一个using namespace std;

原文地址:https://www.jb51.cc/c/112490.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐