简体   繁体   中英

Vector of Class-Object pointers: How to get value at pointer address? C++ and SDL_Rect

I've got a vector of class-object pointers. I declare the vector in main..:

std::vector<Class1*> vector1;
vector1.push_back(&object1);
vector1.push_back(&object2);

The below error occurs. This is just the simplest variant of trying to access data contained within the class pointed to by the vector.

Ex:

Main.cpp:

std::cout << vector1[0]->rect->w << std::endl;

Class1.h

SDL_Rect rect{100, 100, 50, 50};

The above results in a red underline of the word 'Vector1' with the error "Expression must have a valid pointer type".

EDIT:

Forgot to mention that I'm trying to get to a SDL_Rect contained within the Class-Objects pointed to by the vector... Not sure how/if that changes anything. I'll provide more complete code when I'm off work.

The code I've provided works if I simply specify a variable of a normal type such an int (where 'age' below is an int):

 std::cout << vector1[0]->age << std::endl;

But since I'm specifying an SDL_Rect in the example from Main.cpp I get the error I mentioned. Anyone know what the peculiarity is?

for(int i = 0; i < vector1.size(); i++)
{
    vector1[i]->width += offset;
}

Dereference the pointer with -> as you normally would.

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