zoukankan      html  css  js  c++  java
  • 内建类型零初始化的问题

    比如有如下这样一段代码,我们很快就能意识到,x 和ptr开始的值都是未定义的,但是sc却很明显会调用其默认构造函数,得到合理的初始化。

    class someclass{

    public:

      someclass():val(){}

    private:

       int val;

    }

    void foo(){
    int x;
    int *ptr;

    someclass sc;

    ......

    }

    在C++中,处理基础类型(int, bool, float, double, 指针类型等)跟处理类类型还是有一定差别的。基础类型并不存在所谓的默认构造函数用于初始化。

    在模板编程中,可以采用如下的方案,使得即使对于内置类型,也可以得到合适的初始化,整型初始化成0,指针类型也初始化成0。

    template <typename T> 
    void foo() 
    { 
        T x = T();    // x is zero (or false)ifT is a built-in type 
    } 

    template <typename T> 
    class MyClass { 
      private: 
        T x; 
      public: 
        MyClass() : x() {  // ensures that x is initialized even for built-in types 
        } 
        … 
    }; 

  • 相关阅读:
    css布局模型
    HTML元素分类
    《水经注》卷三十五
    《水经注》卷二十八
    沧浪之水
    网页布局基础
    IndexError: tuple index out of range
    树回归-CART
    树回归-CART
    支持向量机SVM
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/4240715.html
Copyright © 2011-2022 走看看