C ++ 11上的嵌套类成员访问 [英] Nested class member access on C++11
问题描述
在C ++ 11中,我尝试通过以下方式从嵌套类访问封闭类的成员变量:
In C++11, I am trying to access a member variable of an enclosing class from a nested class in the following way:
struct Enclosing {
int a;
struct Nested {
int f() {
return a;
}
};
};
即使使用带有-std = c ++ 11的g ++ 4.7.2也无法编译,产生以下形式的错误消息:
Even this doesn't compile using g++4.7.2 with -std=c++11, producing error messages of this form:
error: invalid use of non-static data member 'Enclosing::a'
据我了解,C ++ 11将嵌套类视为该类的成员,因此据说嵌套类可以访问该封闭类的所有其他成员。我做错什么了吗?
As far as I understand, C++11 treats a nested class as a member of the class, so that supposedly a nested class can access every other member of the enclosing class. Did I do something wrong? Thanks in advance.
更新:
虽然我的问题似乎有一个在下面的答案中,我不认为这将被标记为重复。
While my question seems to have an answer below, I am not convinced this shall be flagged as duplicate.
我知道在C ++ 11标准之前有关嵌套类和封闭类之间关系的讨论。
I am aware of discussions on the relationship between nested classes and enclosing classes before the C++11 standard, after a lot of searching before posting a question.
以前的相关讨论在C ++ 11中引用了一些更新,例如 C ++嵌套类的可访问性
Previous relevant discussions like this cite some "updates" in C++11, e.g. C++ nested classes accessibility
但是至少从我读过的答案来看,这不是很清楚,C ++ 11在这个问题上与旧版本完全不同。
But it was not very clear, at least from answers I've read, the full extent that C++11 is "different" from older versions on this matter.
我的问题的解决方案存在于较旧的线程中,例如
嵌套类访问封闭类的私有数据成员,这一事实必须指出,但是它使我看起来很愚蠢。但是我并没有得到将C ++ 11置于上下文中的任何答案。至少,我认为我的问题不能等同于C ++ 11标准之前提出的问题。
Technically the solution to my question exists in older threads such as Nested class' access to enclosing class' private data members, a fact that had to be pointed out, however inane it makes me seem. But I did not come by any such answer that puts C++11 into context; at least, I don't think my question can be fairly deemed a "duplicate" of a question asked before the C++11 standard.
推荐答案
为结束这个问题,我将其作为一个答案:
To close this question I'll take this as an answer:
不,它不被视为类的成员,它只作用于内部就像其他任何东西一样。您将需要一个Enclosing实例来访问其成员。
"No, it's not treated as a member of the class, it's just scoped inside of it like anything else. You'll need an instance of Enclosing to access it's members."
- 此注释和其他一些注释解决了我的代码中的问题。基本上,这对于C ++ 11仍然适用。
这篇关于C ++ 11上的嵌套类成员访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!