简体   繁体   English

如何返回一个指针 function?

[英]How to return a pointer function?

I'm new to c++, I'm asked for class work to do a function that takes a doubly linked list and copy it's elements into a singly linked list then returns it, however, I was given this function's declaration only, when I made the function it's either not returning anything or it gives me the error below, I understand the linked list code but I don't understand using a pointer and the returning part, can someone explain this to me?我是 c++ 的新手,我被要求让 class 工作来做一个 function,它采用一个双向链表然后将它的元素复制到一个单向链表中,但是当我给出这个函数的声明时,我只返回它的元素, function 它要么不返回任何东西,要么给我下面的错误,我理解链表代码,但我不明白使用指针和返回部分,有人可以向我解释一下吗? and how to make it work?以及如何使它工作? I'm unable to find explanation to this online, or maybe I am searching the wrong keywords.我无法在网上找到对此的解释,或者我正在搜索错误的关键字。 Any help is appreciated.任何帮助表示赞赏。

template <class T>
SinglyLinkedList<T>* DoublyLinkedList<T>:: Function() {

SinglyLinkedList<T> list1;

DLLnode<T>*p = head;

while (p!=NULL) {

list1.addtoHead(p->value);
p=p->next;

}

return list1;

}

//error: cannot convert ‘SLL<int>’ to ‘SLL<int>*’ in return

1) Using a pointer for this is stupid. 1)为此使用指针是愚蠢的。 But that's what you've been told to do.但这就是你被告知要做的事情。

2) If you use a pointer then this function will return an address. 2)如果你使用指针,那么这个 function 将返回一个地址。 That's what pointers are.这就是指针。 You cannot change that.你无法改变这一点。 The trick is to dereference the pointer when you try to print.诀窍是在您尝试打印时取消引用指针。 That way it won't print an address but will instead print what the pointer is pointing at.这样它就不会打印地址,而是会打印指针指向的内容。 If you need help with this then post your printing code.如果您需要这方面的帮助,请发布您的打印代码。

3) Here's how you do it with pointers 3) 以下是使用指针的方法

template <class T>
SinglyLinkedList<T>* DoublyLinkedList<T>:: Function() {
    SinglyLinkedList<T>* list1 = new SinglyLinkedList<T>();
    DLLnode<T>*p = head;
    while (p!=NULL) {
        list1->addtoHead(p->value);
        p=p->next;
    }
    return list1;
}

This is the second occaision in recent days when posters have been told to do something stupid by their university professors.这是最近几天海报被他们的大学教授告知做一些愚蠢的事情的第二次事件。 Oh well.那好吧。

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

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