我有这样的代码:
class outer{
int x;
class inner{
int y;
}
void print(int t_x){
std::cout << t_x;
}
}
有没有办法只创建内部类的实例?如果可能的话,这个对象是否可以访问 outer::print 函数?
最佳答案
Is there a way to create only instance of class inner?
是的,你可以让outer
创建与 static
一样多的实例独立实例(例如 inner
成员函数中的静态成员或局部变量)如你所愿。
And if this is possible, will this object have acces to
outer::print
function ?
没有。 outer::print()
仅适用于 outer
的实例,所以至少是 outer
的参数或本地实例将需要。
outer
和 inner
类声明完全独立于实例化。这只是关于范围:
inner
类型仅在private
处可见outer
类范围(可以使用通过函数接收的auto
之外的匿名outer
类型来规避)-
inner
可以访问任何public
,protected
和private
outer
的成员(特殊范围特权) -
outer
可以访问任何public
inner
的成员像往常一样(没有特殊特权)
关于c++ - 创建嵌套类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45650554/