【问题标题】:Accessing a class object within a class from a class从类访问类中的类对象
【发布时间】:2015-01-12 11:05:33
【问题描述】:

我知道这个标题有点令人困惑,但图表可能会有所帮助。 在一个文件中:

#ifndef ...
#def  ...
#includes (including OListiterator.h>
template <class T>
class OList;
template <class T>
Class OListiterator{
    friend class OList<T>::OList;
    typename OList<T>::Node* iiter;
};
function defs;
#endif

在另一个:

#ifndef ...
#def ...
#includes (one is OList.h)
template<class T>
class OListiterator;
template <class T>
Class OList{
     friend class OListiterator<T>::OListiterator;
     public:
          class Node{
          };
      //things
};
//functions
#endif

这是我自己和协助我的 TA 认为可行的,但我被抛出错误:节点没有在 OList 中命名类型。有人知道为什么/如何解决这个问题吗?如果我需要发布更多内容,请告诉我。

【问题讨论】:

    标签: c++ class iterator nodes


    【解决方案1】:

    这里似乎存在依赖关系。 OList 需要OListIterator,反之亦然。解决这个问题的方法是改变你的设计,这样就不需要这种依赖了。尝试将您的OListIterator 设计放在OList 中。

    【讨论】:

    • 我已经解决了依赖关系。我已经在 OListiterator 中声明了 template 类 OList,并制定了一切,以便 OListiterator 和 OList 可以相互访问。它是唯一无法访问的节点
    【解决方案2】:

    你需要class OList的前向声明:

    // forward declaration
    template <class T>
    class OList;
    
    template <class T>
    class OListiterator{
        friend class OList<T>::OList;
        typename OList<T>::Node* iiter;
    };
    
    template <class T>
    class OList{
         friend class OListiterator<T>::OListiterator;
    public:
        class Node{
        };
    };
    

    Demo

    请注意,friend class OList&lt;T&gt;::OList; 仅等同于 friend class OList&lt;T&gt;;,因为 OList&lt;T&gt;::OList 是在 OList&lt;T&gt; 范围内注入的类名。

    【讨论】:

    • @Anton 我已经完成了前向声明和朋友类声明,如您所示。
    • @Eric 很可能您在某些使用OListiterator 的代码中没有包含包含OList 定义的头文件。看看我提供的演示,看看你的代码有什么不同。
    • 我删除了 OListiterator 构造函数中的一个函数定义,该构造函数调用 OList 并将其设置为第一个节点,从而消除了问题。但是,当我随后编译时,我现在在 OList(也称为 OListiterator)中遇到了一个问题,即无效使用不完整类型 OListiterator。
    • @Eric 等等,你的意思是你的 .cpp 文件中有这些模板类定义吗?
    • @Eric 所以你包括他们自己的 .h 文件?
    【解决方案3】:

    当您将OList 的成员Node 命名为好友时,编译器需要OList 的整个定义来确保存在这样的成员。

    解决方案是打破依赖关系。为什么列表节点需要访问列表迭代器的内部?在我看来,它应该是相反的。

    【讨论】:

    • 我认为这也可能是问题所在。但是,当我尝试打破依赖关系时,我的 OList 类就会中断。如何给它 OList 的完整定义??
    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2015-05-23
    • 2011-06-05
    • 1970-01-01
    • 2015-05-09
    • 2021-05-05
    • 2020-01-12
    相关资源
    最近更新 更多