查看以下简化示例代码:
class Foo {
private:
struct bar {
int private_value; // only used for internal stuff of class Foo
int public_value;
};
public:
class iterator {
public:
iterator(Foo::bar* c)
:curr{ c }
{
}
int& operator*() { return curr->public_value; }
int* operator->() { return &curr->public_value; }
private:
Foo::bar* curr;
};
void some_function();
};
void Foo::some_function()
{
Foo::iterator it = get_iterator(); // get an iterator from function
*it // this gives only curr->public_value
// what to add to iterator to have acces of private value from iterator class?
}
我想在函数中使用迭代器,并从中获取private_value
。有什么方法可以在迭代器中创建函数,以便仅Foo类可以从迭代器访问private_value
吗?我不允许在迭代器中返回整个* bar结构,因为只有public_value
的用户才可以使用foo
答案 0 :(得分:0)
只需在迭代器中使周围的类成为朋友即可
class Foo {
private:
struct bar {
int private_value; // only used for internal stuff of class Foo
int public_value;
};
public:
class iterator {
public:
iterator(Foo::bar* c)
:curr{ c }
{
}
int& operator*() { return curr->public_value; }
int* operator->() { return &curr->public_value; }
private:
Foo::bar* curr;
friend class Foo; // friend
};
void some_function();
};
有时候您看不到树林中的森林...