내부 클래스가 개인 변수에 액세스 할 수 있습니까?
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 '라는 멤버가 없습니다.
내부 클래스는 정의 된 클래스의 친구입니다.
그렇습니다. 유형의 객체는 유형 객체의 Outer::Inner
멤버 변수 var
에 액세스 할 수 있습니다 Outer
.
그러나 Java와 달리 유형 Outer::Inner
의 개체와 상위 클래스 의 개체 간에는 상관 관계가 없습니다 . 부모 자식 관계를 수동으로 만들어야합니다.
#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();
}
내부 클래스는 외부 클래스의 모든 멤버에 액세스 할 수 있지만 부모 클래스 인스턴스에 대한 암시 적 참조는 없습니다 (Java의 이상한 점과 달리). 따라서 외부 클래스에 대한 참조를 내부 클래스에 전달하면 외부 클래스 인스턴스의 모든 것을 참조 할 수 있습니다.
Anything that is part of Outer should have access to all of Outer's members, public or private.
Edit: your compiler is correct, var is not a member of Inner. But if you have a reference or pointer to an instance of Outer, it could access that.
var is not a member of inner class.
To access var, a pointer or reference to an outer class instance should be used. e.g. pOuter->var will work if the inner class is a friend of outer, or, var is public, if one follows C++ standard strictly.
Some compilers treat inner classes as the friend of the outer, but some may not. See this document for IBM compiler:
"A nested class is declared within the scope of another class. The name of a nested class is local to its enclosing class. Unless you use explicit pointers, references, or object names, declarations in a nested class can only use visible constructs, including type names, static members, and enumerators from the enclosing class and global variables.
Member functions of a nested class follow regular access rules and have no special access privileges to members of their enclosing classes. Member functions of the enclosing class have no special access to members of a nested class."
참고URL : https://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables
'programing tip' 카테고리의 다른 글
미학과 geom_text를 사용할 때 범례에서 'a'제거 (0) | 2020.08.10 |
---|---|
파이썬의 클래스 상수 (0) | 2020.08.10 |
magento의 캐시 관리에서 "Flush Magento Cache"와 "Flush Cache Storage"의 차이점은 무엇입니까? (0) | 2020.08.10 |
strace가 인수를 축약하는 것을 방지 하시겠습니까? (0) | 2020.08.10 |
C #에서 읽기 전용 지역 변수를 허용하지 않는 이유는 무엇입니까? (0) | 2020.08.10 |