[英]Access members of nested class
class A
{
class B
{
int x;
}
public:
void printX() { std::cout << ????; }
}
How can I access the x variable from the A class function? 如何从A类函数访问x变量? I can't make it static either...
我也不能使其静止...
I tried everything but it either tells me I need an object in order to access it or the compiler doesn't find the function. 我尝试了所有操作,但是它要么告诉我我需要一个对象才能访问它,否则编译器找不到该函数。
it either tells me I need an object [...]
它要么告诉我我需要一个物体[...]
Think about that. 考虑一下。 Because that's exactly what the problem is here.
因为这正是问题所在。
If you instantiate an A
, you don't also get a B
. 如果实例化一个
A
, 那么您也不会得到B
A nested class isn't a member variable of the enclosing class. 嵌套类不是封闭类的成员变量。 It's really just another way to change the namespace of a class.
实际上,这只是更改类名称空间的另一种方法。
So, you need an instance of B
. 因此,您需要一个
B
的实例。 Perhaps a member of A
? 也许是
A
的成员?
class A
{
class B
{
public:
int x;
} mB;
public:
void printX() { std::cout << mB.x; }
};
You don't ever declare an instance of the class B inside A. You need to do something like this: 您永远不会在A中声明类B的实例 。您需要执行以下操作:
class A
{
class B
{
public:
int x;
};
B b;
public:
void printX() { std::cout << b.x; }
};
You don't. 你不知道 You do need an object in order to use the x variable.
您确实需要一个对象才能使用x变量。 You could, however make it static.
您可以将其设为静态。 The problem with your example is x is not public.
您的示例的问题是x不公开。 Placing B inside A does not make B part of A, it only changes B's scope.
将B放在A内并不能使B成为A的一部分,而只是改变B的范围。
From this example it kinda looks like you're after inheritance instead. 在此示例中,有点像您在继承继承。 This would give you the effect you're after ( access to all B's methods and variables without making an object. )
这将为您带来想要的效果(无需使用对象即可访问所有B的方法和变量。)
Class B
{
protected:
int x;
}
Class A : B
{
void printX() { std::cout << x; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.