C ++,为什么在结构/类中不需要前向声明 [英] C++, why is forward declaration not required in structs/classes

查看:58
本文介绍了C ++,为什么在结构/类中不需要前向声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,为什么要编译以下内容:

In C++, why does the following compile:

struct test {
    void foo() { this->bar++; }
    int bar;
};

但不是以下内容:

void foo() { bar++; }
int bar;

要清楚一点,我确实了解到,在第二种情况下, foo 缺少 bar 的前向声明并且不会编译.但是我不明白为什么第一个不会因为相同的原因而失败.

To be clear, I do understand that in the second case foo lacks a forward declaration of bar and does not compile. I however do not understand why the first one does not fail for the same reason.

推荐答案

如果是结构,则成员变量的作用域在该结构内可用.因此,如果您在结构中定义一个函数,则该变量将在该函数中可用.

In case of a structure, scope of the member variable is available within the structure. So if you define a function within a structure that variable will be available within the function.

但是,第二种情况并非如此.

But that is the not the case in second scenario.

这篇关于C ++,为什么在结构/类中不需要前向声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆