我正在尝试使用类编写链接列表,并且希望它具有特定的格式。
例如,如果我有三个分别称为p1,p2和p3的数据以及一个名为list的链表;我想像打击一样排列它们。
list.insert(p1).insert(p2).insert(p3);
我试图返回该对象,但是没有用。这是我的代码。
#include<iostream>
using namespace std;
class linked_list {
public:
int *head;
linked_list();
~linked_list();
linked_list insert(int data);
};
linked_list::linked_list()
{
head = NULL;
}
linked_list::~linked_list()
{
int *temp;
int *de;
for (temp = head;temp != NULL;) {
de = temp->next;
delete temp;
temp = de;
}
delete temp;
//delete de;
}
linked_list linked_list::insert(int data)
{
int *temp;
temp = new int;
*temp = data;
temp->next = NULL;
if (head == NULL) {
head = temp;
}
else {
int* node = head;
while (node->next != NULL) {
node = node->next;
}
node->next = temp;
// delete node;
}
//delete temp;
return *this;
}
int main(){
linked_list l1;
int p1,p2,p3;
l1.insert(p1).insert(p2).insert(p3);
return 0;}
@ Jarod42得到了您的答案,尽管周围有许多越野车,但您想要的是这样的。
要链接的函数必须返回对当前对象实例的引用。
这里是一个Foo
类,它更改其_data
成员并多次链接。
#include <iostream>
class Foo
{
private:
int _data;
public:
Foo(int data) : _data(data) {}
~Foo()
{
}
// change the value of data then return a reference to the current Foo instance
Foo &changeData(int a)
{
_data = a;
return *this;
}
void printData()
{
std::cout << _data << std::endl;
}
};
int main()
{
Foo f(1);
f.changeData(2).changeData(3);
f.printData();
}
请注意,我从要链接的函数中返回Foo&
,这是您所缺少的小技巧。
希望它对您有帮助:)