extern类声明用法是否符合C ++标准?

问题描述

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具有可比性。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...