c++ - 使用基于范围的 for 循环取消引用向量指针
问题描述
这是我的 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
,我得到一个操作员错误<<
。在这里取消引用的正确方法是什么?
解决方案
您需要重载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;
}
住在神螺栓上
或者没有朋友:
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);
}
住在神螺栓上
推荐阅读
- android - 在 Google Scene Viewer 中添加 Google Pay 按钮或自定义操作
- excel - 使用 excel VBA,为什么我的 sub 似乎使用 Application.run 运行了两次?
- r - 由 r/data.table 中评估的第一个元素设置的列类型
- python - 为什么 C# 从 python 服务器获取扭曲的图像?
- c++ - 我可以在现代 C++ 中的随机数范围内排除一个数字或数字子范围吗?
- linear-algebra - 热证明以下身份(雅可比)
- python - python列表中的负值
- scala - 来自 scalawithcats 书:值 asRight 不是类型参数 A 的成员
- c - 通过将数学运算符添加到字符串来制作目标数字时的打印结果
- ios - 应用内购买 IOS 未获得批准 - Flutter