未命名的 structclass
** 允许使用未命名的 struct
(类型没有名称)
void foo()
{
struct /* No name */ {
float x;
float y;
} point;
point.x = 42;
}
要么
struct Circle
{
struct /* No name */ {
float x;
float y;
} center; // but a member name
float radius;
};
然后
Circle circle;
circle.center.x = 42.f;
但不是匿名的 struct
(未命名的类型和未命名的对象)
struct InvalidCircle
{
struct /* No name */ {
float centerX;
float centerY;
}; // No member either.
float radius;
};
注意:有些编译器允许匿名 struct
作为扩展名。
Version >= C++ 11
-
lamdba 可以看作是一个特殊的无名的
struct
。 -
decltype
允许检索未命名的struct
的类型 :decltype(circle.point) otherPoint;
-
未命名的
struct
实例可以是模板方法的参数:void print_square_coordinates() { const struct {float x; float y;} points[] = { {-1, -1}, {-1, 1}, {1, -1}, {1, 1} }; // for range relies on `template <class T, std::size_t N> std::begin(T (&)[N])` for (const auto& point : points) { std::cout << "{" << point.x << ", " << point.y << "}\n"; } decltype(points[0]) topRightCorner{1, 1}; auto it = std::find(points, points + 4, topRightCorner); std::cout << "top right corner is the " << 1 + std::distance(points, it) << "th\n"; }