首页 > 解决方案 > 使用基于范围的 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,我得到一个操作员错误<<。在这里取消引用的正确方法是什么?

标签: c++pointersdereference

解决方案


您需要重载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);
}

住在神螺栓上


推荐阅读