我有 2 个类(class) - A and B
.类 A
有成员(member)list<int>
和一种方法 addData()
向此列表添加一个数字。二等类B
有一个函数 displayContent()
- 它遍历类 A
的列表并打印其内容(添加的数字)。我面临的问题是我无法访问 private
(不能更改为公共(public))字段 list
类A
来自新实例化的对象(来自类 B
)。我想问一下如何用getters/setters
来实现, 或 copy constructor
?
最佳答案
在 displayContent_a 中,您标识的“a”未定义,因为在该函数或类中您从未声明过变量“a”。一个简单的解决方案是将类型 A 的对象传递给函数,该函数确定要显示哪些 A 对象的列表:
void displayContent_a(A& a) {
//this uses the a from the parameter
for (auto x = a.a.begin(); x != a.a.end(); x++) { //use a.a because we want to access the list
cout << *x << endl;
}
}
但是,这还不够,因为 B 无法访问 A 的私有(private)数据。要解决此问题,您必须让 B 成为 A 的 friend 。这可以通过以下方式完成:
class B; //forward declare B so it can be used in friend declarations in A
class A
{
//... your content
friend class B;
}
关于c++ - 从一个类访问私有(private)字段到另一个与 C++ 中的前一类无关的类(OOP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51112603/