【问题标题】:C++ List Iterators accessing different elements in the same objectC ++列表迭代器访问同一对象中的不同元素
【发布时间】:2011-10-21 15:13:46
【问题描述】:

对于列表迭代器,我可以访问不同的元素

但我只能访问每个对象的一件事 例如

class student{
private : 
string firstname;
string lastname;
// some other variables //etc...  

public: 
// some functions here ....
};

在列表中,我可以使用列表迭代器访问和打印所有名字 但我如何打印 列表中的名字后跟姓氏?

【问题讨论】:

  • 什么是列表?一个 std::list?
  • 为什么你不能对姓氏做同样的事情呢?

标签: c++ class list object


【解决方案1】:

您可以像打印firstname 一样打印lastname。如果你在类的成员函数中打印它,那么你可以这样做:

std::cout <<firstname <<" " <<lastname << std::endl;

如果你写了一些 get 函数,并且你从类的非成员函数中打印出来,那么你可以这样做:

student s;
//...
std::cout <<s.getFirstname() <<" " <<s.getLastname() << std::endl;

你也可以在类中添加operator&lt;&lt;好友函数,如下:

class student{
private : 
    string firstname;
    string lastname;
    // some other variables //etc...  

public: 
    // some functions here ....
    friend std::ostream& operator<<(std::ostream & out, const student &s)
    {
       return out << s.firstname <<" " <<s.lastname;
    }
};

然后这样做:

std::list<student> students;
//...

for(std::list<student>::iterator it = students.begin(); it != students.end(); it++ )
{
      std::cout << *it << std::endl;
}

你甚至可以这样做:

student s;
//...
std::cout << s << std::endl; //it prints firstname and lastname by calling operator<<

【讨论】:

    【解决方案2】:

    这就是我认为您在谈论的:如果不是,请提供更多详细信息。

    我认为你有一个 std::liststudent,就像

    std::list<student> studentList;
    //add student instances to list
    

    然后你正在迭代它,像这样:

    for(std::list<student>::it = studentList.begin(); it != studentList.end(); ++it)
    {
        std::cout << it->getFirstName() << std::endl;
    }
    

    如果是这种情况,只需为it-&gt;getLastName()添加一点:

    for(std::list<student>::it = studentList.begin(); it != studentList.end(); ++it)
    {
        std::cout << it->getFirstName() << " " << it->getSecondName() << std::endl;
    }
    

    【讨论】:

      【解决方案3】:

      简单! cout 名字后跟姓氏。

      cout << lIter->firstName << " " << lIter->lastName << endl ;
      // firstName, lastName are private. So, intead write getters and call those on list iterator.
      

      还是我理解错了问题?

      【讨论】:

      • 嗯,我这样做了,它只保留了 endl 之前 cout 中的最后一件事,出于某种原因,这是你的情况下的姓氏
      猜你喜欢
      • 1970-01-01
      • 2021-04-17
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 2010-12-21
      • 1970-01-01
      相关资源
      最近更新 更多