【问题标题】:C++ - using std::list, how do you print a linked list of an object's private members?C++ - 使用 std::list,如何打印对象私有成员的链表?
【发布时间】:2019-10-28 00:05:39
【问题描述】:

它适用于我将 Unit 的成员公开时。将变量更改为私有,我如何访问/打印它们?

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

}

【问题讨论】:

  • 这与std::list 没有任何关系。一个类的私有成员和公共成员的工作方式相同,无论它们存储在哪里或您如何尝试访问它们。您肯定已经了解了私人和公共在课堂上的作用吗?
  • 要克服private,您需要实现getter 或提供其他方法来访问namequantity 的私有成员或将showTheContent 设为朋友。谷歌一下。

标签: c++ list class linked-list private


【解决方案1】:

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

你可以打开成员的访问,你可以添加getter/setter,实现访问者模式——有很多选项。最简单的就是开放访问(公开所有内容):你应该根据教授给你的任务来判断。

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

void showTheContent(const list<Unit>& l)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 2013-12-30
    • 1970-01-01
    • 2021-02-15
    • 2016-01-10
    • 2013-06-10
    • 2011-04-25
    相关资源
    最近更新 更多