简体   繁体   中英

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. I have class Queue and struct Element inside. I have constructor for Element which asign value and pointer to next element. I want to make function Push in Queue class which just create Element object (and pass value to Push function). 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. So it have to modify my Queue object. My Push 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?

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:

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

The only thing you need to assure, is that Element can access Queue::front and Queue::back . For instance, if they are private members of Queue , then you can make Element a friend of Queue , something like:

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

Edit: haven't noticed that you do modify Queue inside Element .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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