初学者 C++使用访问器/获取器从私有成员变量(二维数组)中提取数据

发布于 2024-09-25 01:41:04 字数 789 浏览 0 评论 0原文

这里完全是菜鸟,只有大约 2 个月的 C++ 经验(没有其他背景),所以对我宽容一点。

我正在为编程作业编写战舰游戏。游戏网格是 15X20,我试图将网格作为类 player 的私有成员变量。

我的问题是:

如果类 player 有一个私有成员变量:

char playgrid[15][20];

是否有任何原因导致访问器函数(定义为:

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

不起作用)?

它让我头疼。我得到的错误是:

c2065:“playgrid”未声明的标识符

,指向访问器定义中的行 return playgrid[val1][val2]

在试图解决这个问题时,我已经成功地使用 getter 从其他私有成员变量中提取值,因此在创建对象后,对象内的其他所有内容都可以正常工作。我绝对没有拼写错误或滥用大小写。在我的构造函数中,playgrid 初始化如下:

int i, j;

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

给出了什么?

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] within 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

电影里的梦 2024-10-02 01:41:04

访问器有什么原因吗?
函数,定义为:

char getgrid(int index1, int index2)
{
返回播放网格[索引1][索引2];
}

行不通?

是的。像这样声明的函数不会是类的成员函数。你可能的意思是

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

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)
{
    // ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文