好的,所以我对所有这些运算符重载的东西感到困惑,语法对我来说很奇怪,而且我也不是很擅长编程。因此,显然在互联网上环顾四周,我认为我打印出对象的唯一方法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;
}
那么,当我在 main 中调用 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”中。或者没有?