0

Consider I have this piece of code:

#include <iostream>

using namespace std;

enum TEXTURE { SAND, GRASS, DIRT, ROCK, SNOW };

class grid
{
    public:
        TEXTURE type;
        string str;
};

grid layer[5];

int main()
{
    layer[0].str = "AAAAA";
    layer[1].str = "A A A";
    layer[2].str = " A A ";
    layer[3].str = "  A  ";
    layer[4].str = "AA AA";

    grid *ptr;
    ptr = &layer[0];

    if(*ptr.str.at(1) == 'A')
        cout << "TRUE!\n";
}

When I attempt to compile, it give me this error:
error: request for member str in ptr, which is of non-class type grid*
*I want to fix this so I can access the member variable str through ptr.
How do I fix it?

Edited by Chuckleluck: Dumb formatting >_<

2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by mike_2000_17
0

The dot operator and member function call have priority over the dereference operator. This means that the expression *ptr.str.at(1) is evaluated as *(ptr.str.at(1)), and that is why you get the error "str" is not a member of the pointer type grid*.

To fix it, you just need parentheses, like so: (*ptr).str.at(1). Or, C++ provides a shorter syntax for this very common operation, which is as follows: ptr->str.at(1), where the arrow p-> basically replaces the (*p)..

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.