类中未定义/未初始化的默认值 [英] Undefined / Uninitialized default values in a class

查看:136
本文介绍了类中未定义/未初始化的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有此类:

class A
{
public:
  A () {}
  A (double val) : m_val(val) {}
  ~A () {}
private:
  double m_val;
};

创建A的实例后,如何检查m_val是否已初始化/定义? 换句话说,有没有办法知道m_val是否已初始化/定义?我想Python中的defined运算符类似. (但是如果我错了,请纠正我.)

Once I create an instance of A, how can I check if m_val has been initialized/defined? Put it in other words, is there a way to know if m_val has been initialized/defined or not? Something along the lines of the defined operator in Python, I suppose. (But correct me if I'm wrong.)

我想通过以下方式修改类和c-tor:

I thought of modifying the class and the c-tors the following way:

class A
{
public:
  A () : defined(false) {}
  A (double val) : m_val(val), defined(true) {}
  ~A () {}
private:
  double m_val;
  bool defined;
};

您如何评价此解决方案?有什么建议吗?

How do you rate this solution? Any suggestion?

TIA, 克里斯

推荐答案

您需要在默认构造函数中设置一个明智的默认值,否则它的值是不确定的.这基本上意味着它将是一个随机值-可以是0,NaN或2835.23098-除非您明确设置,否则无法分辨.

You'll need to set a sensible default value in the default constructor, otherwise its value is undefined. Which basically means it will be a random value -- could be 0, NaN, or 2835.23098 -- no way to tell unless you set it explicitly.

class A
{
public:
  A () : m_val(0.0) {}
  A (double val) : m_val(val) {}
  ~A () {}
private:
  double m_val;
};

这篇关于类中未定义/未初始化的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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