【发布时间】: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 或提供其他方法来访问name和quantity的私有成员或将showTheContent设为朋友。谷歌一下。
标签: c++ list class linked-list private