我正在尝试打印map <Object, int>
的内容。这是有问题的代码:
void Inventory::print_initial_inventory()
{
for(auto p : inventory) {
std::cout << p.first << " : " << p.second << std::endl;
}
}
std::ostream& operator<<(std::ostream& outstream, Inventory& inv)
{
outstream << inv.first << "\nNumber of parts: " << inv.second << std::endl;
return outstream;
}
我知道问题出在p.first
吗?因为std::cout
不知道如何打印对象,所以我尝试使operator<<
重载,但是我不确定该怎么做。谁能指出我正确的方向?
编辑,这是我再次尝试解决此问题的方法。建议我将键类型传递给operator<<
重载。这是我的代码:
void Inventory::print_initial_inventory()
{
for(auto x : inventory) {
std::cout << x.first << " : " << x.second << std::endl;
}
}
std::ostream& operator<<(std::ostream& outstream, Auto_Part& inv)
{
outstream << "Type: " << inv.type << "\nName: " << inv.name << "\nPart Number: " << inv.part_number << "\nPrice: $" << inv.price << std::endl;
return outstream;
}
我仍然遇到指向x.first
的无效的二进制表达式错误。
答案 0 :(得分:1)
std::cout
是std::ostream
对象。对于某些基本类型(you can check them out here),std::ostream
已将operator<<
重载。如果您想在类中使用operator<<
(例如class MyType
),则必须自己重载该运算符。
对于诸如std::ostream
这样的内置C ++类型,您可以在类外部执行此类重载(因为否则必须修改std::ostream
),其语法为:
std::ostream& operator<< (std::ostream& s, const MyType& arg)
{
/* enter you implementation here */
return s;
}
更多信息here。
答案 1 :(得分:1)
我知道问题出在
p.first
吗?因为std::cout
不知道 如何打印object
,所以我试图重载<< operator
, 但我不确定该怎么做。
运算符重载的基础知识可以在这篇文章中找到:What are the basic rules and idioms for operator overloading? 我强烈建议您在继续操作之前先阅读此内容
在您的情况下,我发现了两个基本问题:
Key
班。尤其是,如果不提供std::map
,则如何将元素插入Inventory
(operator<
类的成员)中?由于Key
类是用户定义的,因此需要给出一个。您可以在以下SO帖子中了解有关此内容的更多信息:std::maps with user-defined types as key
Key
类型提供operator<<
。可以按照以下步骤进行操作:例如,假设class Key
class Key
{
int member;
public:
Key(const int a): member(a){}
// provide operator< for your Key type
bool operator<(const Key& other)const { return this->member < other.member; }
// provide operator<< for Key class like follows
friend std::ostream& operator<<(std::ostream& out, const Key& key);
};
// implement outside the class
std::ostream& operator<<(std::ostream& out, const Key& key)
{
// simply for this case
return out << key.member;
}
现在您可以以类似的方式为operator<<
类提供Inventory
。
// now in Inventory class
class Inventory
{
std::map<Key, int> inventory;
public:
Inventory(const std::map<Key, int>& m): inventory(std::move(m)) {}
// declared as friend, so that you can access the private member(map)
friend std::ostream& operator<<(std::ostream& out, const Inventory& inv);
};
// implement outside the class
std::ostream& operator<<(std::ostream& out, const Inventory& inv)
{
for(const auto& entry: inv.inventory )
out << entry.first << " Number of parts: " << entry.second << std::endl;
return out;
}
// in the main
int main()
{
Key key1{1};
Key key2{2};
std::map<Key, int> tempInvObj{{key1, 11}, {key2, 12}};
Inventory obj{tempInvObj};
std::cout << obj;
return 0;
}
输出:
1 Number of parts: 11
2 Number of parts: 12