[英]Does C++ provide a way to access a class within a class without the scope resolution operator?
Does C++ provide a way to declare an object that has the type of a class within a class (eg foo_class::bar_class_in_class
in the example below) without having to use the scope resolution operator, as it does for a class within a namespace (eg foo_namespace::bar_class_in_namespace
in example below)? C ++是否提供了一种方法来声明一个类中具有类类型的对象(例如下面示例中的foo_class::bar_class_in_class
),而不必使用范围解析运算符,就像它对命名空间中的类所做的那样(例如foo_namespace::bar_class_in_namespace
在下面的例子中)?
namespace foo_namespace {
class bar_class_in_namespace {
};
}
class foo_class {
public:
class bar_class_in_class {
};
};
int main() {
using namespace foo_namespace;
bar_class_in_namespace bar_0;
// Can I access bar_class_in_class without having to use the
// the scope resolution operator?
foo_class::bar_class_in_class bar_1;
}
This question is the same as Can we alias a class name the way we do in namespaces? 这个问题与我们在命名空间中的方式别名一样可以吗? , with the minor difference that this question asks explicitly about a class within a class. ,这个问题明确地询问了一个班级中的一个课程的细微差别。
Yes, C++ offers a way to access the type. 是的,C ++提供了一种访问类型的方法。 What you need is a type alias. 你需要的是一个类型别名。 Using 运用
using bar_class_in_class = foo_class::bar_class_in_class;
allows you to use bar_class_in_class
in place of foo_class::bar_class_in_class
. 允许您使用bar_class_in_class
代替foo_class::bar_class_in_class
。 This is scoped so if you do it in main
, you can only see the alias in main
这是作用域,所以如果你在main
执行它,你只能在main
看到别名
Do note that you can also "change the name" of the inner type 请注意,您还可以“更改内部类型的名称”
using my_type = foo_class::bar_class_in_class;
does the same thing as above, but you would use my_type
as the type name. 做与上面相同的事情,但你会使用my_type
作为类型名称。 This can be a nice convenience. 这可以是一个很好的方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.