简体   繁体   English

C++:如何将“this”object 作为指针引用传递

[英]C++: how to pass 'this' object as pointer reference

The question is not very clear, because I know that 'this' is const* and I can't modify pointer.这个问题不是很清楚,因为我知道'this'是 const* 并且我不能修改指针。 I have class Queue and struct Element inside.我里面有 class 队列和结构元素。 I have constructor for Element which asign value and pointer to next element.我有 Element 的构造函数,它分配值和指向下一个元素的指针。 I want to make function Push in Queue class which just create Element object (and pass value to Push function).我想让 function 推入队列 class ,它只创建元素 object (并将值传递给推送功能)。 My Element constructor is我的元素构造函数是

Element(Queue*& queue, int value)

i must pass Queue object, because in Queue class i have pointer to first and last element of Element structure.我必须通过队列 object,因为在队列 class 中,我有指向元素结构的第一个和最后一个元素的指针。 So it have to modify my Queue object.所以它必须修改我的队列 object。 My Push function:我的推送 function:

    Element* x = new Element(this, x);  [i know that this can't work as i said this is const]

main:主要的:

Queue* q = new Queue();
q.Push(5);

How to pass object 'q' as parameter to constructor of Element?如何将 object 'q' 作为参数传递给 Element 的构造函数?

EDIT: Element constructor:编辑:元素构造函数:

Queue::Element::Element(Queue*& queue, int x)
{
    if (queue->front)
    {
        Element* tmp = queue->front;
        while (tmp->next)
        {
            tmp = tmp->next;
        }
        tmp->next = this;
        this->value = x;
    }
    else
    {
        queue->front = this;
        queue->back = this;
        this->value = x;
    }
}

Just pass a simple pointer to the Element() constructor:只需将一个简单的指针传递给 Element() 构造函数:

Queue::Element::Element(Queue* queue, int x)

The only thing you need to assure, is that Element can access Queue::front and Queue::back .您唯一需要保证的是Element可以访问Queue::frontQueue::back For instance, if they are private members of Queue , then you can make Element a friend of Queue , something like:例如,如果它们是Queue的私有成员,那么您可以让Element成为Queuefriend ,例如:

class Queue {
//...
friend class Element;
//...

Edit: haven't noticed that you do modify Queue inside Element .编辑:没有注意到您确实在Element中修改了Queue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM