OOP:用于计数输出的方法
OOP: Method for cout output
我必须创建一个方法,它在屏幕上打印所有收集的数据,这是我的尝试:
bool UnPackedFood::printer() {
cout << " -- Unpacked Products --" << endl;
cout << "barcode: " << getBarcode() << endl;
cout << "product name: " << getBezeichnung() << endl << endl;
cout << "weight: " << getGewicht() << endl;
cout << "price" << getKilopreis() << endl;
return true;
}
In my main:
UnPackedFood upf;
cout << upf.printer();
这显示了正确的输出,但它仍然返回给我一个bool值,这实际上是我不需要的。
您应该重载输出流的<<
操作符。然后,当您输入cout << upf
时,它将打印您的产品。
看看这个例子,并尝试做一些类似于下面的代码片段:
class UnPackedFood {
...
public:
...
friend ostream & operator<< (ostream &out, const UnPackedFood &p);
};
ostream & operator<< (ostream &out, const UnPackedFood &p) {
out << " -- Unpacked Products --" << endl;
out << "barcode: " << p.getBarcode() << endl;
out << "product name: " << p.getBezeichnung() << endl << endl;
out << "weight: " << p.getGewicht() << endl;
out << "price" << p.getKilopreis() << endl;
return out;
}
三种可能的解决方案:
-
不做
cout << upf.printer();
,输出是不需要的,因为函数本身做输出。 -
不写入
printer
函数的输出,而是附加到字符串后返回字符串 -
为
UnPackedFood
做一个重载的operator<<
,所以你可以只做std::cout << upf;
相关文章:
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 从 c++ 中的实例化进程获取输出的可靠方法是什么?
- is_permutation方法从 #include<algorithm> 显示错误的输出
- 将多个效果与 libSox 链接并读取输出数据的正确方法
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 如何使用方法覆盖在输出屏幕上显示堆栈整数值
- 有没有一种简单的方法可以将矢量 int 集转换为字符串输出?
- 使控制台输出是否"verbose"的最快方法
- 如何优雅地实现具有可变输出的单个方法?
- 我试着了解方法覆盖是如何工作的,不知道为什么输出 2
- 快速获取C Eclipse中图形输出的方法
- 为什么我没有使用班级的tostring方法获得输出
- 将QProcess输出发送到TextEdit的最佳方法
- 在不同于依赖DLL的文件夹中输出已编译目标的正确方法是什么
- 有没有一种简单的方法可以将系统命令的输出转换为字符串
- 如何在c++中将方法的cout输出输出到流文件中
- 与参数同名的方法会导致不同的输出
- 当输出参数是类时,如何在C++中调用COM方法
- 使用 COUT 的 C++ 静态方法输出始终为 1
- 日志系统应该使用哪种输出方法