Passing Struct Array to Function by reference
I was wondering how to pass a struct array by reference into a function. I found how to do it with pointers but wanted to learn with references too. Here is my code thus far.
struct employeeType
{
string firstName;
...
double monthlyBonus;
};
void readEmpData(ifstream& infile, employeeType *emp, int length);
I thought I just did employeeType& emp or employeeType& emp[] but get error开发者_高级运维s and everything I have googled just did pointers.
Here is the full code at pastebin for clarification for my learning experiment: http://pastebin.com/6NfZ3LC4
Is the array of a fixed size? If not, you could use a template:
template <unsigned int N>
void myFunction(Foo (&arr)[N])
{
// arr[0] etc.
}
Naturally, this will only work for compile-time arrays:
void f()
{
Foo a[10];
myFunction(a); // OK
Foo * b = new Foo[11];
myFunction(b); // error, nonsense, b is a pointer, not an array
}
(If your array is always of the same size, you can skip the template and put the size into the argument directly. Note that "array" isn't one type in C++, but rather, T[N]
is a different type for each N
. That's why you cannot have a single function for "all arrays".)
I assume you want readEmpData to read in an array of employees from a file. In this case, the caller wouldn't know how many employees there are and so the array and its length should be output parameters. An appropriate signature would be:
void readEmpData(ifstream & infile, employeeType *& emp, int & length);
or
employeeType * readEmpData(ifstream & infile, int & length);
You could also define the operator <<
for employeeType and read using STL:
vector<employeeType> employees;
copy(istream_iterator(file), istream_iterator(), back_inserter(employees));
A pointer can be a pointer to a single object, or to an array of objects. Makes no difference. The reason you haven't found any references to arrays is that it's usually redundant.
*emp
will access a single object, or the first object of an array.
emp[0]
is exactly the same as *emp
with a different syntax. They both behave exactly the same.
emp[1]
will get the second object in an array. How does C++ know you passed an array to the function? It doesn't. It expects you to keep track of whether the pointer points to an array, and the size of the array.
精彩评论