问题描述
class My_Container
{
/*...*/
class iterator
{
extern class const_iterator;
Node* _ptr;
public:
bool operator==(const iterator& other) {return _ptr == other._ptr;}
bool operator==(const const_iterator& other) {return _ptr == other._ptr;}
};
class const_iterator
{
Node* _ptr;
public:
bool operator==(const const_iterator& other) {return _ptr == other._ptr;}
bool operator==(const iterator& other) {return _ptr == other._ptr;}
};
}
如果我省略extern class const_iterator;
声明,它不会编译。
是否符合C ++ 17标准?
内部类可以访问另一个内部类的私有成员吗?
解决方法
外部类声明用法是否符合C ++标准?
否,这不符合标准。类不能具有存储类说明符。
内部类可以访问另一个内部类的私有成员吗?
与其他任何班级相同;它可以访问公共成员。该示例访问类外部的私有成员,因此它的格式不正确。
如果我省略extern类const_iterator,它不会编译;声明。
使用常规的前向声明:
class const_iterator;
class iterator
{
// ...
};
class const_iterator
{
// ...
};
我建议以另一种方式解决问题:首先定义const_iterator
。使iterator
隐式转换为const_iterator
。使const_iterator
仅与const_iterator
具有可比性。