c++ - 如何让 2 个 C++ 类了解彼此的数据成员?

标签 c++ class iterator datamember

我的任务是创建一个类似于标准库 List 的类。我无法让迭代器正常工作,因为它必须在从末尾递减时访问链表的尾部。这是我的头文件的一部分:

typedef int T;//for now; eventually will be templated
class list;//**forward declaration, doesn't let other classes know about _tail.**
class Node
{
    //this works fine; class definition removed to make post shorter
};
class list_iterator
{
    private:
        Node* _node;
        list* _list;
    public:
        //constructor
        list_iterator& operator--(){_node=_node?(_node->_prev):(_list->_tail);return *this;}
        //some other declarations
};
class list
{
    friend class list_iterator;
    private:
        Node/*<T>*/ *_head,***_tail**;
        int _size;
    public:
        typedef list_iterator iterator;
        //some constructors and other method declarations
        iterator begin() const {iterator it(_head);return it;}
        iterator end() const {iterator it(0);return it;}
        //more method declarations
};

我试图将重要部分加粗,但只是用星号将它们包围起来。 注意:大部分成员函数都定义在cpp文件中;他们都碰巧被删除了一个简短的帖子。

最佳答案

你只需要将operator--的方法定义移出类,放在list之后(或者放在源文件中(可能是更好的主意。声明保留在头文件中) ).

Note: Leave the declaration inside list_iterator

class list_iterator
{
    /* STUFF */
    list_iterator& operator--();
 };
class list
{ 
     /*  STUFF */ 
};

// Now list_iterator::operator-- can see all the members of list.
list_iterator& list_iterator::operator--()
{
    _node=_node?(_node->_prev):(_list->_tail);
    return *this;
}

与其他一些答案所暗示的不同。 Friendship does NOT break encapsulation .事实上,通过使类接口(interface)的友元部分增加封装(当正确完成时)。但是,它确实将 friend 与类(class)紧紧地联系在一起。

这正是您想要的迭代器。为了使迭代器有效地工作,它需要了解类的内部结构,因此它通常是友元(或内部类)。它增加了类的可用性而不暴露类的内部工作,代价是它将迭代器与类紧密耦合(因此,如果您更改类,您将需要更改迭代器的实现(但这并不意外)).

关于c++ - 如何让 2 个 C++ 类了解彼此的数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11526728/

相关文章:

c++ - 如何在 Protocol Buffer 中设置嵌套消息的字段?

c++ 11:战俘的简称?

c++ - Qt uint 类型是如何序列化的?

c++ - 有没有一种方法可以换出成员变量而不用在子构造函数中单独传递它们?

c++ - 迭代某个类的 vector 列表 (C++)

c++ - 我是否需要手动将 PCREDENTIAL.CredentialBlob 清零?

java - 如何使用循环来创建新对象?

java - 创建一个类的方法并在主类中调用它

c++ - 如何检查 STL 迭代器是否指向任何东西?

c++ - 为什么迭代器需要 CopyConstructible 和 CopyAssignable?