这是我main()函数中的代码:
std::map<int, std::string> candyMap;
std::vector<House*> houseVector;
std::ifstream abodeFile{houseFile};
std::string houseLine;
if(abodeFile.is_open())
{
while(getline(abodeFile, houseLine))
{
houseVector.push_back(new House(houseLine, candyMap));
}
}
std::cout << std::setw(11) << " ";
for(auto i:houseVector)
{
std::cout << std::setw(11) << i;
}
我正在尝试打印houseVector中的元素。显然,使用上面的代码,我获得了元素的地址。当我执行*i
时,出现<<
的操作员错误。取消引用的正确方法是什么?
答案 0 :(得分:2)
您需要重载ostream <<
运算符,例如:
class House
{
int member;
public:
explicit House (int i) : member(i) {}
friend ostream& operator<<(ostream& os, const House& house);
};
ostream& operator<<(ostream& os, const House& house)
{
os <<house.member << '\n';
return os;
}
在Godbolt上直播
或者没有朋友:
class House
{
int member;
public:
explicit House (int i) : member(i) {}
std::ostream &write(std::ostream &os) const {
os<<member<<'\n';
return os;
}
};
std::ostream &operator<<(std::ostream &os, const House& house) {
return house.write(os);
}
在Godbolt上直播