当我将 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/