Cliffnotes:
I got a chain of methods to work, as I expected in one case, but in the other case something funny happens.
I expect these two examples to have the same result:
As expected, the example
Not as the expected example
I did a lot of chaining using Javascript, so when I found out that you can bind class methods in a similar way in C ++, I wanted to try. However, I ran into some problems. I'm not sure if this is the chain causing the problems, or something else.
I am chaining by returning links to this. For instance:
Class LLL
{
public:
LLL & addNode( ... );
and then the add Node method ends with:
...
return *this;
}
There are 2 relevant classes and 3 suitable methods.
, LLL Node, Node. , Node int ( guid) next prev. LLL. , , .
, , :
// Create 3 node objects & change their guids
Node node1; node1.change(1); // change(n) outputs "-n-"
Node node2; node2.change(2);
Node node3; node3.change(3);
// Create a linear linked list object
LLL lll;
// Add the nodes to the LLL and show the LLL
lll.addNode(node1).addNode(node2).addNode(node3).show();
// Expected and real output:
-1
Node:
, , :
Node nod;
LLL lll;
lll.addNode(nod.change(1)).addNode(nod.change(2)).addNode(nod.change(3)).show();
-1--2--3-123
-3--2--1-111
, .
, , Node .
, . , -, , node.h, node.cpp, lll.h, lll.cpp main.cpp:
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <ctime>
using namespace std;
class Node
{
public:
Node();
Node(int guidIn);
Node(const Node & nodeIn);
Node & change(int guidIn);
void commonConstructor();
Node * next();
void next(Node * nodeIn);
Node * prev();
void prev(Node * nodeIn);
Node & show();
private:
int guid;
Node * nextNode;
Node * prevNode;
};
class LLL
{
public:
LLL();
~LLL();
LLL & addNode(const Node & nodeIn);
LLL & show();
private:
Node * head;
};
Node::Node()
{
guid = 0;
commonConstructor();
}
Node::Node(int guidIn)
{
guid = guidIn;
commonConstructor();
}
Node::Node(const Node & nodeIn)
{
guid = nodeIn.guid;
commonConstructor();
}
Node & Node::change(int guidIn)
{
guid = guidIn;
cout << "-" << guidIn << "-";
return *this;
}
void Node::commonConstructor()
{
nextNode = NULL;
prevNode = NULL;
}
Node * Node::next()
{
return nextNode;
}
void Node::next(Node * nodeIn)
{
nextNode = nodeIn;
}
Node * Node::prev()
{
return prevNode;
}
void Node::prev(Node * nodeIn)
{
prevNode = nodeIn;
}
Node & Node::show()
{
cout << guid;
return *this;
}
LLL::LLL()
{
head = NULL;
}
LLL::~LLL()
{
Node * temp = head;
while(head)
{
temp = head;
head = head->next();
delete temp;
}
}
LLL & LLL::addNode(const Node & nodeIn)
{
Node * tempNode = new Node(nodeIn);
if(!head)
{
head = tempNode;
} else
{
Node * temp = head;
while(temp->next())
{
temp = temp->next();
}
temp->next(tempNode);
}
return *this;
}
LLL & LLL::show()
{
Node * temp = head;
while(temp)
{
temp->show();
temp = temp->next();
}
return *this;
}
int main()
{
Node node;
LLL lll;
lll.addNode(node.change(1)).addNode(node.change(2))
.addNode(node.change(3)).show();
cout << "\n";
return 0;
}