如何防止调用结构的默认构造函数? [英] How to prevent a struct's default constructor to be called?

查看:41
本文介绍了如何防止调用结构的默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以防止结构体的默认构造函数被调用?

Is there any way to prevent the default constructor of a struct to be called?

我的项目中有几个结构体,其中一些结构体在任何情况下我都不能让默认构造函数被调用(这会导致我的代码中出现很多不需要的行为).

I have several structs in my project and some of them I can not let the default constructor to be called at any circumstances (that will be cause a lot of unwanted behaviour in my code).

PS.:任何在编码时仅指示我一些特殊结构(无法使用默认构造函数实例化)正在错误地"实例化的解决方案对我来说都很好.对于我的情况,一个简单的编译器警告就足够了!

PS.: Any solution that just indicates me when coding that some of that special structs (that can not be instantiated with the default constructor) are being instantiate "wrongly" is fine for me. A simple compiler warning should be enough for my case!

推荐答案

你不能.

本质上,

  • struct 的所有字段都必须初始化为某个值.
  • struct 不能有无参数构造函数
  • 无参数构造函数将被隐式调用,没有办法绕过它.
  • all fields of a struct must be initialized to some value.
  • a struct cannot have a parameter-less constructor
  • the parameter-less constructor will be implicitly called, there's no way around it.

如果您需要此类行为或检查您的设计,请使用 class.

Either use a class if you need such behavior or review your design.

这篇关于如何防止调用结构的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆