开发者

Beginner C++ Using accessors / getters to pull data from a private member variable (2D array)

开发者 https://www.devze.com 2023-01-18 01:44 出处:网络
total noob here with about 2 months of C++ experience (no other background) so go easy on me. I am writing a battleship game for a programming assignment. The game grid is 15X20 and I am trying to h

total noob here with about 2 months of C++ experience (no other background) so go easy on me.

I am writing a battleship game for a programming assignment. The game grid is 15X20 and I am trying to have the grid as a private member variable of the class player.

My question is:

If the class player has a private member variable:

char playgrid[15][20];

Is there any reason why an accessor function, defined as:

char getgrid(int index1, int index2)
{
    return playgrid[index1][index2];
}

wouldn't work?

It's doing my head in. The error I am getting is:

c2065: 'playgrid' undeclared identifier

which points to the line return playgrid[val1][val2] w开发者_JAVA百科ithin the accessor definition.

While trying to figure this out, I've successfully used my getters to pull values from other private member variables, so everything else is working properly within the object after it is created. I'm definitely not misspelling anything or misusing capitalization. In my constructor, playgrid is initialized as follows:

int i, j;

for (i=0; i<15; i++)
{
    for (j=0; j<20; j++)
    {
        playgrid[i][j]='o';
    }
}

What gives?


Is there any reason why an accessor function, defined as:

char getgrid(int index1, int index2)
{
return playgrid[index1][index2];
}

wouldn't work?

Yes. A function declared like this would not be a member function of a class. You probably meant

char player::getgrid(int index1, int index2)
{
    // ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消