内部类可以访问私有变量吗? [英] Can inner classes access private variables?
本文介绍了内部类可以访问私有变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Outer {
class Inner {
public:
Inner() {}
void func() ;
};
private:
static const char* const MYCONST;
int var;
};
void Outer::Inner::func() {
var = 1;
}
const char* const Outer::MYCONST = "myconst";
当我用类Outer :: Inner编译时出现错误:没有成员名为`var' / p>
This errors out when I compile with class Outer::Inner' has no member named `var'
推荐答案
内部类是它在其中定义的类的朋友。
所以,类型 Outer :: Inner
的对象可以访问类型为 var
> c>。
An inner class is a friend of the class it is defined within.
So, yes; an object of type Outer::Inner
can access the member variable var
of an object of type Outer
.
与Java不同,类型 Outer :: Inner
和父类的一个对象。您必须手动创建父子关系。
Unlike Java though, there is no correlation between an object of type Outer::Inner
and an object of the parent class. You have to make the parent child relationship manually.
#include <string>
#include <iostream>
class Outer
{
class Inner
{
public:
Inner(Outer& x): parent(x) {}
void func()
{
std::string a = "myconst1";
std::cout << parent.var << std::endl;
if (a == MYCONST)
{ std::cout << "string same" << std::endl;
}
else
{ std::cout << "string not same" << std::endl;
}
}
private:
Outer& parent;
};
public:
Outer()
:i(*this)
,var(4)
{}
Outer(Outer& other)
:i(other)
,var(22)
{}
void func()
{
i.func();
}
private:
static const char* const MYCONST;
Inner i;
int var;
};
const char* const Outer::MYCONST = "myconst";
int main()
{
Outer o1;
Outer o2(o1);
o1.func();
o2.func();
}
这篇关于内部类可以访问私有变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文