好吧,所以我对所有这个操作符重载的东西感到困惑,语法对我来说只是奇怪的,反正我在编程方面也不是那么棒。因此,在互联网上环顾四方,显然我认为使用cout <<
打印对象的唯一方法就是让它超载。所以我有一个对象矢量,通常如果我只是有一个整数或字符串的常规向量,那么我只需要使用一个迭代器并遍历每个对象,然后对其进行解引用以打印出其中的内容,但我不认为该技术正在为对象工作: - /这是我迄今为止......帮助!如何通过重载<<运算符来打印出矢量中的对象?
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 << "\t\t\t" << b.type << "\t\t\t" << 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在向量中添加该对象的信息?它获取信息,然后将其添加到变量名称,类型和大小,然后将其放入矢量“bar”中。或没有?
等什么。 BarOne中有'vector'吗?另外,你调试吗? –
2013-02-10 18:06:16
你的'BarOne'类拥有'BarOne'对象的'vector'吗?在我看来,你需要重新思考你的课堂设计。 – Praetorian 2013-02-10 18:08:30
我不认为让BarOne拥有'BarOne'的'矢量'并不一定是错误的,只要这个矢量在施工时没有填充。 – 2013-02-10 18:09:58