C++ - 使用 std::list,如何打印对象私有(private)成员的链表?

标签 c++ list class linked-list private

当我将 Unit 的成员公开时,它会起作用。将变量更改为私有(private),如何访问/打印它们?

我的教授没有教过遍历对象链表(在本例中为 )的方法以及如何访问该对象的私有(private)成员。我是否实现 getter 和 setter?我真的迷路了,因为我对链表和使用列表库还很陌生。

#include <iostream>
#include <list>
#include <string>

using namespace std;

class Unit {
private:
    string name;
    int quantity;
public:
    Unit(string n, int q){
        name = n;
        quantity = q;
    }
};


void showTheContent(list<Unit> l)
{
    list<Unit>::iterator it;
    for(it=l.begin();it!=l.end();it++){
        //
        cout << it->name << endl;
        cout <<  it->quantity << endl;
//        cout << &it->quantity << endl;  // shows address
    }
}

int main()
{
    // Sample Code to show List and its functions

    Unit test("test", 99);

    list<Unit> list1;
    list1.push_back(test);
    showTheContent(list1);

}

最佳答案

私有(private)说明符的目标是防止从此类外部访问成员。您对 Unit 类的设计很荒谬,因为您对每个人都隐藏了成员,而且您也不在此类内部使用它们。

您可以打开成员的访问权限,您可以添加 getters/setters,实现访问者模式——有很多选择。最简单的就是开放访问(make everything public):你应该根据教授给你的任务来判断。

顺便说一下,在您的 showTheContent 函数中,您正在制作列表的完整拷贝,您可能不打算这样做。改用 const 引用:

void showTheContent(const list<Unit>& l)

关于C++ - 使用 std::list,如何打印对象私有(private)成员的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58584441/

相关文章:

c# - 从子文件夹链接 dll

c++ - 转发声明问题

c++ - 是什么导致此 Visual Studio Pro 2013 警告?

python - 如何通过按 Enter 键引入以换行符\n 结束的输入?

C++,将 vector<char> 写入 ofstream 会跳过空格

c# - 使用介于两者之间的方法将 c# List 转移到另一个列表

c# - 从 List<T> 到数组 T[] 的转换

java - 从另一个类访问私有(private)最终静态 double

c++ - 简单的编译错误但没有意义

c++ - 在程序员创建时自动将类型派生类(不是实例)添加到列表中。 C++