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)?
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. 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
. This is scoped so if you do it in main
, you can only see the alias in 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. This can be a nice convenience.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.