C++ 从类返回指针
对于我的编程类,我必须编写一个链表类。我们必须包含的函数之一是next()。此函数将返回列表中下一个元素的内存地址C++ 从类返回指针,c++,pointers,linked-list,C++,Pointers,Linked List,对于我的编程类,我必须编写一个链表类。我们必须包含的函数之一是next()。此函数将返回列表中下一个元素的内存地址 #include <iostream> using namespace std; class Set { private: int num; Set *nextval; bool empty; public: Set(); <some return type>
#include <iostream>
using namespace std;
class Set {
private:
int num;
Set *nextval;
bool empty;
public:
Set();
<some return type> next();
};
<some return type> Set::next() {
Set *current;
current = this;
return current->next;
}
int main() {
Set a, *b, *c;
for (int i=50;i>=0;i=i-2) a.insert(i); // I've ommited since it does not pertain to my question
// Test the next_element() iterator
b = a.next();
c = b->next();
cout << "Third element of b = " << c->value() << endl;
return 0;
}
#包括
使用名称空间std;
类集{
私人:
int-num;
Set*nextval;
布尔空;
公众:
Set();
next();
};
Set::next(){
设置*电流;
电流=这个;
返回当前->下一步;
}
int main(){
集合a、*b、*c;
for(inti=50;i>=0;i=i-2)a.insert(i);//我已经提出了,因为它与我的问题无关
//测试下一个元素()迭代器
b=a.next();
c=b->next();
coutSet*
是正确的。此函数中存在一个相当愚蠢的错误:
Set* Set::next() {
Set *current;
current = this;
return current->next;
}
最后一行应该是return current->nextval
。否则,您试图返回指向next
函数的指针…可能不是您想要的,永远。:-luqui是正确的,尽管您的next函数过于复杂,但没有理由复制此指针,这很愚蠢。请在代替:
Set* Set::next() {
return nextval;
}