Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile error with "this" keyword in a struct constructor? - C++

I have the following:

int main()
{
    struct A
    {
        unsigned char x, y;

        A(unsigned char x, unsigned char y)
        {
            this.x = x; // Error: expression must have class type.
            thix.y = y; // Error: expression must have class type.
        }
    };

    return 0;
}

How do I properly refer to the x and y variables of the struct A and not the x and y variables of the constructor parameters of A?

Thank you.

like image 208
Hatefiend Avatar asked Dec 25 '22 08:12

Hatefiend


1 Answers

this is a pointer, so you need to dereference it:

this->x = x;
this->y = y;

It doesn't matter if it's a struct or class, it's a pointer in both cases. The only different between the two is that struct members are public by default, while class members are private by default.

Also, it's not a good idea to define a struct or class inside of a function. Do it at global scope instead.

like image 163
dbush Avatar answered Dec 28 '22 09:12

dbush