无法使用外部类对象访问内部类成员 [英] Can't access inner class member with outer class object
问题描述
#include <iostream>
class Outer
{
int o;
public:
void setOuter(int o)
{
this->o=o;
}
class Inner
{
public:
int i;
int retOuter(Outer *obj)
{
return obj->o;
}
};
};
int main(int argc, char **argv) {
Outer::Inner obj;
obj.i=20;
std::cout<<"Inner i = "<<obj.i<<std::endl;
Outer *obj1=new Outer;
obj1->setOuter(40);
std::cout<<"Outer o = "<<obj.retOuter(obj1)<<std::endl;
obj1->Inner::i =50; //Access the inner class members by Outer class object!
}
以上代码中的所有内容都可以与最后一行分开.为什么我不能使用外部类对象访问内部类成员?外部类对象应该具有 class Outer
的所有公共成员访问权限,并且当我创建一个由外部类包含的内部类对象时,其行为如何!
Everything in the above code is fine apart from the last line. Why I am not able to access the Inner class member with an Outer class object? Outer class object should have all the public member access of class Outer
And how is the behavior when I create an Inner class object as it is contained by an Outer class!
推荐答案
内部
只是一个在不同范围内定义的类.和说没什么不同
Inner
is just a class defined at a different scope. It's no different than saying
class Inner
{
public:
int i;
int retOuter(Outer *obj)
{
return obj->o;
}
};
然后
Inner::i =50
这显然是不可能的,因为 i
不是 static
.
which obviously isn't possible because i
isn't static
.
声明内部类不会自动为外部类声明该类型的成员,您可以使用该语法访问该内部类.
Declaring an inner class doesn't automagically declare a member of that type for the outer class which you can access using that syntax.
现在,类似:
class Outer
{
int o;
public:
void setOuter(int o)
{
this->o=o;
}
class Inner
{
public:
int i;
int retOuter(Outer *obj)
{
return obj->o;
}
} innerMember;
// ^^^
// declare a member
};
int main(int argc, char **argv) {
Outer *obj1=new Outer;
obj1->innerMember.i =50; //Access the inner class members by Outer class object!
}
会工作的.
这篇关于无法使用外部类对象访问内部类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!