好吧,所以我對所有這個操作符重載的東西感到困惑,語法對我來說只是奇怪的,反正我在編程方面也不是那麼棒。因此,在互聯網上環顧四方,顯然我認爲使用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