Hank Stalica said:
So I've made a linked list class.
I have a function that initiates this class, opens a file, parses it,
and then inserts nodes into this temporary class.
What I would like to do is then have it return that temporary class so I
can assign it to a permanent class in the main program.
I've written an assignment operator.
So something like this is what I want to do:
MyList loadMyList(string file)
{
MyList temp;
//Do stuff to load temp.
return temp;
}
Ewwww. That won't work. It returns a temporary, so behavior is undefined.
Use a parameterized constructor instead:
class MyList
{
public:
MyList(std::string file)
{
do stuff here to load records from file to list
}
(other public methods here, maybe)
private:
(internal data representation)
}
in main:
MyList list;
list = loadMyList(fileName);
Ewwww, yuck. No, no, no. Soooooo many things wrong with that: returning
temporaries, unneeded copying and assigning, etc., etc., etc..
Do this instead:
#include <iostream>
#include <string>
int main(int Beren, char * Luthien[])
{
std::string FileName(Luthien[1]); // get file name from cmmd-line arg.
MyList list (FileName); // construct list from file
...
return 0;
}
I suspect that my datatype MyList is wrong...maybe it should be MyList*
or MyList&?
Nope. That part you got right. But you need to learn about constructors.
I'm assuming, also, that you're just implimenting lists for programming
practice, or for a class. But for "real" code, use std::list instead.
Then instead of MyList, you could use std::list<MyType> where "MyType"
could be just about any kind of copy-constructable type imaginable.
Something like this, perhaps (untested, incomplete; do the rest yourself):
#include <iostream>
#include <string>
#include <list>
struct EmployeeRecord
{
std::string first_name;
std::string last_name;
double wage_rate;
}
void
BuildList
(
std::list<EmployeeRecord> const & EmpList,
std::string const & FileName
)
{
EmployeeRecord TempRec;
Do stuff here to load employee records from file to EmpList.
For each record in file, create a temporary EmployeeRecord object,
then push a copy of the temporary object to the back of the list.
Mixed C++ code and pseudocode:
(open the file)
while (1)
{
(try to get a record)
if (EOF) break;
(Load the record into TempRec)
EmpList.push_back(TempRec);
}
return;
}
int main(int Beren, char * Luthien[])
{
// Get name of employee-records file from cmmd-line argument:
std::string FileName(Luthien[1]);
// Make a list:
std::list<EmployeeRecord> EmpList;
// Dump employee records from file into list:
BuildList (EmpList, FileName);
// Do other necessary stuff:
...
return 0;
}