指针未在C 类中初始化

pointer not initialized in c++ class

本文关键字:初始化 指针      更新时间:2023-10-16

i'am new with c and Pointers,我对此C 代码有问题。通常,此代码必须显示" True",但事实并非如此。预先感谢。

class Trie{  
   public:
      Trie* root;
      int color;
      Trie(){
         color=0;
       }
       ~Trie(){
       }
  };
 int main(){
   Trie test;
   if(test.root==nullptr)cout<<"true"<<endl;
  }

c和c ,与java和c#不同,出于性能原因,请勿自动零命名记忆或对象成员,因为如果您只想设置自己的设置,则没有点覆盖内存无论如何价值;缺点是您必须非常谨慎,以确保您不要首先使用非初始化的数据。

要解决问题,您可以在构造函数中设置成员,也可以在初始化列表中设置成员:

Trie() {
    this->color = 0;
    this->root  = nullptr;
}

或:

Trie() :
    color ( 0 ),
    root  ( nullptr )
{    
}

至于您的color值,请考虑使用元组,因为不能保证int将是32位整数(假设您需要存储0-255 RGB值):

>
struct RgbColor {
    uint8_t r;
    uint8_t g;
    uint8_t b;
    RgbColor() :
        RgbColor( 0, 0, 0 ) {
    }
    RgbColor(uint8_t r, uint8_t g, uint8_t b) :
        r(r),
        g(g),
        b(b) {
    }
    RgbColor(uint32_t rgb) :
        r( ( rgb >> 24 ) & 0xFF ),
        g( ( rgb >> 16 ) & 0xFF ),
        b( ( rgb >>  8 ) & 0xFF ) {
    }
}