C++ Help with pointers for a student
I am trying to create a vector and pass it to a function allowing the vector to be modified. Here is an abridged version of my code that doesn't work.
void addStudent(vector<Student*>*);
int main()
{
vector<Student*> students = new vector<Student*>;
addStudent(students);
return(0);
}
void addStudent(vector<Student*> *students)
{
students->push_back(new Student("bob"));
}
This code is compiling with errors. I 开发者_StackOverflowthink I'm not passing the pointer correctly but I'm not sure.
You've promised to give addStudent
a pointer to a vector:
void addStudent(vector<Student*> *students)
so, use the address-of operator to get a pointer:
vector<Student*> students;
addStudent(&students);
There's nothing here that actually needs dynamic allocation, but if you did, note that new
also returns a pointer:
vector<Student*>* students_ptr = new vector<Student*>();
addStudent(students_ptr);
Another option is to pass by reference:
void addStudent(vector<Student*>& students)
vector<Student*> students;
addStudent(students);
But I prefer the pointer, when the function is going to change its parameter.
Your problem is here:
vector<Student*> students = new vector<Student*>;
students
is declared as a value type but you're assigning it a pointer.
In the future you should include the compiler error in your question.
You probably come from a Java
background... so you'll have to learn to live without new
for a while :)
In C++ there are 2 ways to create objects:
- objects with automatic storage duration (created on the stack)
- objects with dynamic storage duration (created on the heap)
new
creates objects of the second kind, for which YOU must ensure proper disposal (by calling delete
according to text books, but... we'll stay away from this for now).
Here, you don't need new
:
std::vector<Student> students; // create an empty `vector` of `Student` objects
students.push_back(Student("bob")); // push a new Student in the vector
As for the function, you have several possibilities:
- make it return the object
- pass the object by reference
void addStudent(std::vector<Student>& students);
- pass by pointer, but then use the address of operator to get to it
addStudent(&students);
You don't have to use pointers everywhere in C++... in fact, it's probably better you don't, to begin with.
Oh, and you definitely need a good tutorial, that's basic stuff, and you can't get into C++ without the boring basics... sorry :/
精彩评论