如何使用匿名结构或类?
因此,可以声明匿名类或结构,但如何使其有用?
int main() {
class{
int ClassVal;
};
struct{
short StructVal;
};
StructVal = 5; //StructVal is undefined
ClassVal = 5; //ClassVal is undefined too?
return 0;
}
如果您将它们都放在主函数之外,它们也将无法访问。 我问这个只是因为它有点有趣:)
编辑: 为什么主函数外部(全局范围)的 union 必须静态声明 例如:
static struct {
int x;
};
int main() {
//...
}
So, it's possible to declalre anonymous class or struct but how to I make it useful?
int main() {
class{
int ClassVal;
};
struct{
short StructVal;
};
StructVal = 5; //StructVal is undefined
ClassVal = 5; //ClassVal is undefined too?
return 0;
}
if you put both of them outside of main function they will be inaccessible as well.
I'm asking this only because it's somehow intersting :)
EDIT:
Why union outside of main function (at global scope) must be static declared
for example:
static struct {
int x;
};
int main() {
//...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
匿名类和结构可用于直接定义变量:
上面的情况并不常见,但在西蒙·里克特(Simon Richter)在他的回答中描述的联合中使用时非常常见。
Anonymous classes and structures may be used to directly define a variable:
The above is not very common like that, but very common when used in unions as described by Simon Richter in his answer.
这些在嵌套
struct
和union
的形式中最有用:现在
typed_data
被声明为具有成员t
的类型code>、i
、cp
、ucp
、wcp
和len
,最小化其预期用途的存储要求。These are most useful in the form of nested
struct
andunion
:Now
typed_data
is declared as a type with the memberst
,i
,cp
,ucp
,wcp
andlen
, with minimal storage requirements for its intended use.