使用 ostream 作为参考 (C++)
-
26-09-2019 - |
题
我有一个家庭作业,其中头文件提供给我们,并且是不可更改的。我无法弄清楚如何正确使用“显示”功能,所以这里是相关代码。
头文件:
#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& 作为参数。我的问题是,当调用“display”作为一个好的参数时,我在驱动程序文件中使用什么?
解决方案
正如你所说, display
需要一个类型的参数 std::ostream &
.
在您的显示方法实现中,您正在输出 std::cout
这违背了接收输出流作为方法参数的逻辑。这里,参数的重点是 display
调用者将能够提供他选择的输出流。如果他的选择恰好是标准输出,他会写:
x.display(std::cout);
这意味着您的 display
实现应该只输出 Out
参数而不是 std::cout
.
另请注意:
- 你的
display
实现返回一个不应该返回的值(void
返回类型) - 我用
std::
为了清楚起见,在我的答案中添加前缀,但在您的情况下不需要它们,因为头文件包含using namespace std;
.
其他提示
您需要做的是替补上场的所有已使用COUT的地方。还通过COUT像x.display(COUT)的参数。这是因为,COUT是关闭的类型的ostream和所有该初始化中的iostream进行。
在你的显示方法,你是明确使用COUT。但是,这是“标准输出”。该方法更应使用完。因此,在显示屏(),只需更换出COUT的每次出现。
然后使用显示器(COUT); 在您的通话
您没有传递一个ostream对象。它更改为这样:
X.display(cout);
然后在你的类取代COUT所有出现的输出。 此外,显示函数返回一个const的ostream&,而不是无效的。你也应该使用,而不是常量的ostream ostream的引用。
有标准使用的类的操作者以外的:
const ostream & operator<< (const ostream & Out, const Set & set)
{
// display your Set here using out, not cout
return out;
}
这样你就可以做这样的事情:
cout << "This is my set: " << mySet << endl;
不隶属于 StackOverflow