未命名的 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"; }