C++:使用STD::列表,如何打印对象的私有成员的链接列表?
它适用于我公开单位成员的情况。将变量更改为private,如何访问/打印它们 我的教授没有教过在这种情况下迭代对象链表的方法以及如何访问该对象的私有成员。我是否实现了getter和setter?我真的迷路了,因为我对链表和使用列表库很陌生C++:使用STD::列表,如何打印对象的私有成员的链接列表?,c++,list,class,linked-list,private,C++,List,Class,Linked List,Private,它适用于我公开单位成员的情况。将变量更改为private,如何访问/打印它们 我的教授没有教过在这种情况下迭代对象链表的方法以及如何访问该对象的私有成员。我是否实现了getter和setter?我真的迷路了,因为我对链表和使用列表库很陌生 #include <iostream> #include <list> #include <string> using namespace std; class Unit { private: string na
#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);
}
私有说明符的目标是防止从该类外部访问成员。你对Unit类的设计是荒谬的,因为你对每个人都隐藏了成员,而且你也没有在这个类中使用它们 您可以打开对成员的访问,可以添加getter/setter,实现访问者模式——有很多选项。最简单的方法是打开访问权限,让一切公开:你应该根据教授给你的任务来判断 顺便说一下,在Show Content功能中,您正在制作列表的完整副本,而您可能并不打算这样做。改为使用常量引用:
void showTheContent(const list<Unit>& l)
这实际上与std::list没有任何关系。类private和public成员的工作方式相同,无论它们存储在何处,也不管您如何尝试访问它们。当然,您已经了解了private和public在类中的作用?要克服private,您需要实现getter或提供其他方法来访问私有成员的名称和数量,或者让Show内容成为朋友。谷歌。