问题描述
我有这样的代码:
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 theprivate
outer
class scope (can be circumvented using anonymousauto
types outside ofouter
received through functions) inner
has access to anypublic
,protected
andprivate
members ofouter
(special scope priviledges)outer
has access to anypublic
members ofinner
as usual (no special priviledges)
这篇关于创建嵌套类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!