简体   繁体   中英

C++ Pointer Assignment (Point to a Vector)

This is my first post in any forum so please bear with me.

I am writing a C++ program that utilizes a custom class 'Book' with member variables such as title, author and other variables that are stored in strings. Amongst these member variables is a vector for storing objects of type Review (which is another custom class). Now in my driver file (where the main() is located) needs to access that vector (the Reviews vector in each Book object) and make changes to it as well. I realized that I need to utilize a pointer of type vector (eg. vector pointerName ). So I added another member variable to the Books class which is a pointer. The problem I am facing is to point that pointer to the vector. Where can I make this assignment? I tried de-referencing it and pointing it to the vector in the default constructor for the object, but that causes my program to crash at run time without throwing an exception. The line I put in the constructor is *pointer = vector_of_reviews;

I am new to this forum and still learning how to go about posting here so please bear with me if I have made a mistake in my post or if I was unclear or insufficient with my information. Please let me know if I need to post or say anything more to make my stance clear.

Thank You.

To assign a pointer to 'point to' an instance of an object use pointer = &vector_of_reviews .

The & operator gets the address of something, and it's this that you want to assign to the pointer.

*pointer = vector_of_reviews dereferences the pointer (obtains the actual object 'pointed to'). This would more than likely crash if the pointer is yet to be initialised. If the pointer was valid this would perform a value assignment, ie. invoke the vector class's assignment operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM