c++ - 尝试重载输出运算符时,我无法遍历对象 vector

标签 c++ object for-loop vector iterator

我有一个类 CPerson

class CPerson
{
private:
    string name;
    string egn;
public:
    CPerson() {};
    CPerson(string getname, string getegn)
    {
        name = getname;
        egn = getegn;
    }
bool operator < (const CPerson &obj)
    {
        ...
    }
    bool operator ==(const CPerson &obj)
    {
        ...
    }
    friend ostream& operator << (ostream& out, const CPerson &obj) //извеждане в поток - конзола
    {
        ...
    }
    friend istream& operator >> (istream& in, CPerson &obj) //четене от поток - конзола
    {
        ...
    }
    friend ofstream& operator <<(ofstream& out, const CPerson& obj) // извеждане в поток - файл
    {
        ...
    }
    friend ifstream& operator >>(ifstream& in, CPerson& obj) // четене от поток - файл
        {
...
        }

我创建了另一个类 CCity,它有一个对象 vector CPerson

class CCity
{
private:
    string city_name;
    vector <CPerson> people;
public:
    CCity() {};
    CCity(string filename)
    {
        string name, egn;
        ifstream file(filename);
        file >> city_name;
        while (file >> egn >> name)
        {
            people.push_back(CPerson(name, egn));
        }
    }
    friend ostream& operator <<(ostream& out, const CCity& obj)
    {
        vector<CPerson>::iterator iter;
        for (iter = people.begin(); iter != people.end(); iter++)
        {

        }
    }
};

我试图重载输出运算符以便我可以输出我的对象 vector ,但我收到错误“'.begin' 的左侧必须具有类/结构/union ”。我看不出我的代码有什么问题。我有包括和

最佳答案

一开始:

friend ostream& operator <<(ostream& out, const CCity& obj);

没有定义成员函数!将函数(运算符)声明为 friend 使其成为一个独立的函数,即使在类内部定义也是如此。所以里面没有 people 对象。你需要引用obj.people!

那为什么要在循环前面声明iter呢?之后出于任何原因需要迭代器吗?如果不是,最好将其保留在 for 循环的本地。然后你可以另外让类型被推导:for(auto iter = ...auto 将另外覆盖另一个错误:obj is const ,所以 obj.people 也是 const。常量对象的 begin 重载不会返回 iterator,而是 const_iterator!请注意 begin 有两个版本:

iterator begin();
const_iterator begin() const; // <- that one will be called on const objects!

你会打破中间的循环吗?如果没有,您也可以使用基于范围的 for 循环:for(auto& person : obj.people)。再次推导出 person 的类型,因为我们明确告诉 auto 是一个引用,类型将是 Person const&

无论您选择哪种变体,您现在都可以输出人物:

out << *iter;
out << person;

假设他们是公开的,您也可以访问此人的属性:

iter->name;
person.name;

关于c++ - 尝试重载输出运算符时,我无法遍历对象 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59702954/

相关文章:

c++ - 为什么我会收到此错误?二进制 '==' : no operator found which takes a left-hand operand of type 'std::string'

c++ - IO重定向: cout not working in main

java - 计算实例变量增加的次数

javascript - 如何在 JavaScript 中的另一个对象中找到具有属性的对象

c++ - 语法错误/for 循环

c++ - 在 Direct3D 12 中的描述符范围内设置多个描述符

c++ - 什么是对象切片?

javascript - 为什么对象的键只是第一个字符?

php - 使用 php for 循环动态输入名称

java - 循环显示字符串