C++ 实现一项功能,即;插头;流入小溪

C++ 实现一项功能,即;插头;流入小溪,c++,stream,iostream,C++,Stream,Iostream,我实现了一个打印结构/类的内存布局的函数。我希望此函数通过以下方式“插入”到流中: BaseStruct1 struct1; cout << "The struct1 object is:" << endl; cout << OutputObjectLayout(&struct1, sizeof(struct1)) << endl; BaseStruct1 struct1; 无法使过载,我终于自己在这里找到了答案: 下面是一个如何做到这一

我实现了一个打印结构/类的内存布局的函数。我希望此函数通过以下方式“插入”到流中:

BaseStruct1 struct1;
cout << "The struct1 object is:" << endl;
cout << OutputObjectLayout(&struct1, sizeof(struct1)) << endl;
BaseStruct1 struct1;

无法使
过载,我终于自己在这里找到了答案:

下面是一个如何做到这一点的示例:

首先,我们需要定义一个临时类来完成这项工作。临时结构应如下所示:

class WidthSetter {
public:
   WidthSetter (int n) : width_(n) {}
   void operator( )(ostream& os) const {os.width(width_);}
private:
   int width_;
};
WidthSetter setWidth(int n) {
   return(WidthSetter(n));   // Return the initialized object
}
这种行为的要点是WidthSetter将由一个函数构造,并由另一个函数使用。操纵器函数将构造它,它应该如下所示:

class WidthSetter {
public:
   WidthSetter (int n) : width_(n) {}
   void operator( )(ostream& os) const {os.width(width_);}
private:
   int width_;
};
WidthSetter setWidth(int n) {
   return(WidthSetter(n));   // Return the initialized object
}
所有这一切只是返回一个用整数值初始化的WidthSetter对象。这是我们将使用的操纵器,与运算符一致<
myostream << setWidth(20) << "banana";

myostream哎哟!此示例仅显示如何向类添加流输出和输入方法。