【问题标题】:Display List of Class in C++在 C++ 中显示类的列表
【发布时间】:2015-05-22 21:40:14
【问题描述】:

您好,我是编程新手,我正在尝试在 C++ 中显示类列表 我试过这个:

#include <string>
#include <list>
class Person
{
public:
    std::string Name;
    Person();
    virtual ~Person();
}

#include "Person.h"
#include <iostream>
#include <conio.h>
#include <list>
#include <string>
using namespace std;
int main()
{
Person p;
list<Person> lp;
p.Name= "Smith";
lp.push_back(p);
while (it != lp.end())
{
    cout << *it;
    it++;
}
_getch();
return 0;
}

但它什么也没显示,我不知道为什么!有人能帮助我吗 ?谢谢

【问题讨论】:

  • 您不想打印出Person::Name吗?
  • 你真的认为这和名单有关系吗?

标签: c++ list class displayobject


【解决方案1】:

其实cout &lt;&lt; *it; 部分就好了。

您忽略了为您的班级重载operator&lt;&lt;。为了确保一致性,我可能会在创建 Person 时将其更改为需要名称,然后将 Name 设为私有成员,这样外部代码就不会搞砸了:

class Person
{
    std::string Name;
public:
    Person(std::string Name) : Name(Name) {}
    virtual ~Person();

    friend std::ostream &operator<<(std::ostream &os, Person const &p) { 
        return os << p.Name;
    }
}

那么您创建和打印列表的代码可能如下所示:

std::list<Person> people { "Smith", "Jones" };

for ( auto const &p : people)
    std::cout << p << "\n";

【讨论】:

    【解决方案2】:

    如果您想打印出Person::Name 字段,您必须更改您的打印语句

    cout << *it;
    

    cout << it->Name;
    

    这将打印出Person 实例中的名称字段。

    或者,您可以为您的班级重载operator &lt;&lt;,如@JerryCoffin 的回答中所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多