如何通过重载<<运算符来打印矢量中的对象?
How do I print out objects in a vector by overloading the << operator?
好吧,所以我对所有这些运算符重载的东西感到困惑,语法对我来说很奇怪,而且我在编程方面也不太擅长。因此,环顾互联网,我显然认为我使用cout <<
打印对象的唯一方法是重载它。所以我有一个对象向量,通常如果我只有一个int或字符串的正则向量,那么我只需要使用迭代器,遍历每一个,然后解引用它来打印其中的内容,但我认为这种技术对物体不起作用://以下是我迄今为止所掌握的。。。帮助
BarOne.h //my header file
#include <string>
#include <vector>
using namespace std;
class BarOne
{
private:
string name;
string type;
string size;
vector<BarOne> bar; //vector of BarOne objects
vector<BarOne>::iterator it; //iterator for bar
public:
BarOne(); //constructor
void addBottle(string, string, string); //adds a new bottle to bar
void revealSpace();
void printInventory();
friend ostream& operator<<(ostream& os, const BarOne& b);
};
我的实现看起来像:
BarOne.cpp //implementation
#include "BarOne.h"
#include <iostream>
#include <string>
using namespace std;
BarOne::BarOne()
{
//adding 4 default bottles
}
void BarOne::addBottle(string bottleName, string bottleType, string bottleSize)
{
name = bottleName;
type = bottleType;
size = bottleSize;
}
void BarOne::printInventory()
{
for (it = bar.begin(); it != bar.end(); ++it)
{
cout << *it << endl;
}
}
ostream& operator<<(ostream& os, const BarOne& b)
{
os << b.name << "ttt" << b.type << "ttt" << b.size;
return os;
}
那么,当我在主目录中调用printInventory时,它为什么什么都不做呢?我超载做错了吗?语法错误?
好的,这也是主要的:
#include "BarOne.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Tiqo, Peruvian, Wellington, Smooze;
string vodka;
string rum;
string whiskey;
string small;
string medium;
string large;
//default bottles
vector<BarOne> bar; //vector of BarOne objects
vector<BarOne>::iterator it; //iterator for bar
BarOne Inventory; //BarOne object
Inventory.addBottle(Tiqo, vodka, large);
bar.push_back(Inventory);
Inventory.addBottle(Peruvian, rum, medium);
bar.push_back(Inventory);
Inventory.addBottle(Wellington, vodka, large);
bar.push_back(Inventory);
Inventory.addBottle(Smooze, whiskey, small);
bar.push_back(Inventory);
^^^这只是其中的一部分……剩下的只是格式化程序运行时的显示方式。所以好吧,我会试着像别人建议的那样把课程分开。AddBottle将该对象的信息添加到向量中,对吗?它获取信息,然后将其添加到变量名称、类型和大小中,然后放入向量"栏"中。还是没有?
您没有向我们展示您的main()
程序。这段代码,再加上你的类设计混淆了条形图的内容,导致了你看到的行为。
operator <<
实际上可以输出瓶子的数据。但我确信它被调用的BarOne
有一个空的bar
向量。您的addBottle()
不会在任何位置添加任何内容(特别是不会添加到包含的bar
中)。相反,它只是简单地设置外部BarOne
对象的属性(数据成员)。
这种混乱的根源是你的课堂设计,BarOne
显然是用来充当瓶子和酒吧(里面有瓶子)的。
我建议您重新启动并尝试使用单独的Bar
和Bottle
类。
BTW:将本地循环中使用的迭代器保留为类成员不是一个好主意。这种方法迟早会遇到可重入性问题。循环迭代器应该是局部变量,最好作用域为循环。
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 如何在自删除后将对象设置为nullptr
- C++是否可以将fstream对象设置为在每次调用<<
- 如何显示/打印字符串对象?cout & lt; & lt;Int工作,count <<字符串