本文介绍了创建嵌套类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

class outer{
   int x;
   class inner{
     int y;
   }

   void print(int t_x){
     std::cout << t_x;
   }
}

有没有办法只创建内部类的实例?并且如果可能的话,该对象是否可以访问external :: print函数?

Is there a way to create only instance of class inner? And if this is possible, will this object have acces to outer::print function ?

推荐答案

是的,您可以让 outer 创建尽可能多的实例独立实例(例如,作为静态成员或本地实例)您需要的内部静态成员函数中的变量。

Yes, you can let have outer creating as many instance independent instances (e.g. as static members or local variables in static member functions) of inner as you want.

否。 outer :: print()仅可用于 outer 的实例,因此至少有一个参数或本地实例外部是必需的。

No. outer::print() is only available with an instance of outer, so at least a parameter or a local instance of outer will be needed.

outer inner 类声明在实例化方面是完全独立的。它只涉及范围:

The outer and inner class declarations are completely independent regarding instantiation. It's only about the scope:


  • inner 类型仅在 private outer 类范围(可以使用匿名 auto 类型规避在通过功能收到的外部之外)

  • 内部可以访问任何公共受保护的私有成员的外部(特殊权限)

  • 外部可以访问任何公共内部的成员照常(无特殊特权)

  • The inner type is only seen at the private outer class scope (can be circumvented using anonymous auto types outside of outer received through functions)
  • inner has access to any public, protected and private members of outer (special scope priviledges)
  • outer has access to any public members of inner as usual (no special priviledges)

这篇关于创建嵌套类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 06:56