问题
I have an iObj class that take two parameters in its constructor, this object is then passed to another method(Add) of another class(store) that takes object from iObj and stores it in a Linked List (List). The Linked list has a class of its own.
When I run main like this
Store st;
st.Add(iObj(Britain", 1));
st.Add(iObj(Germany", 0.01));
st.Add(iObj(Bhutan", 10));
st.PrintStore();
Nothing is displayed on the screen.
List Implementation.
List::List()
{
head = NULL;
}
void List::insert(iObj* new_node)
{
new_node->next = head;
head = new_node;
}
void List::Print()
{
iObj* temp = head;
while (temp != NULL)
{
std::cout << temp->GetValue()) << "\t";
temp = temp->next;
}
}
iObj Class Implementation.
class iObj
{
public:
iObj(char const* first_name, double value);
char GetValue()
// ~iObj();
// copy constructor
// copy assignment operator
friend class LinkedList;
private:
char* first_name;
double value;
iObj* next;
};
iObj::iObj(char const* first_name, double value) : first_name(new char[strlen(first_name) + 1]), value(value), next(NULL)
{
strcpy_s(this->first_name, (strlen(first_name) + 1), first_name);
}
char* iObj::GetValue()
{
return first_name;
}
Store Implementation. This is where iObj is stored into Linked List (List)
void store::Add(iObj& UserIObj)
{
List LL;
iObj* s1 = new iObj("China", 3.5);
LL.insert(s1);
}
回答1:
Well of course, you are creating a new List everytimes you go into store::Add. So, you're only adding elements to a list on the stack and then destroying it.
You need to put List LL as a member of store not as a local variable.
(Unless List has static members, but I assumed not).
来源:https://stackoverflow.com/questions/31130366/linked-list-class-not-inserting-nodes-when-called-from-another-class-method