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

问题描述 投票:0回答:1

它在我公开该单位的成员时起作用。将变量更改为私有变量,如何访问/打印它们?

我的教授没有教过遍历对象的链接列表的方法(在本例中为)以及如何访问该对象的私有成员的方法。我是否实现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);

}
c++ list class linked-list private
1个回答
1
投票

私有说明符的目标是防止从此类外部访问成员。您对Unit类的设计很可笑,因为您向所有人隐藏了成员,并且也不在此类中使用它们。

您可以打开成员的访问权限,可以添加getters / setters,实现Visitor模式-有很多选项。最简单的方法是打开访问权限(将所有内容公开):您应该根据教授给您的任务进行判断。

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

void showTheContent(const list<Unit>& l)
© www.soinside.com 2019 - 2024. All rights reserved.