指针未在c+中初始化+;班 我是C++和指针的新手,我对C++代码有问题。通常,此代码必须显示“true”,但它不显示。提前谢谢 class Trie{ public: Trie* root; int color; Trie(){ color=0; } ~Trie(){ } }; int main(){ Trie test; if(test.root==nullptr)cout<<"true"<<endl; } class-Trie{ 公众: Trie*根; 内色; Trie(){ 颜色=0; } ~Trie(){ } }; int main(){ Trie试验; 如果(test .root = = nulLpTR)cOUT C和C++,与java和C语言不同,不要因为性能原因自动初始化内存或对象成员,因为如果你只是要设置你自己的值,那么没有两个点重写内存;缺点是你必须非常小心,以确保你不使用未初始化的数据。

指针未在c+中初始化+;班 我是C++和指针的新手,我对C++代码有问题。通常,此代码必须显示“true”,但它不显示。提前谢谢 class Trie{ public: Trie* root; int color; Trie(){ color=0; } ~Trie(){ } }; int main(){ Trie test; if(test.root==nullptr)cout<<"true"<<endl; } class-Trie{ 公众: Trie*根; 内色; Trie(){ 颜色=0; } ~Trie(){ } }; int main(){ Trie试验; 如果(test .root = = nulLpTR)cOUT C和C++,与java和C语言不同,不要因为性能原因自动初始化内存或对象成员,因为如果你只是要设置你自己的值,那么没有两个点重写内存;缺点是你必须非常小心,以确保你不使用未初始化的数据。,c++,C++,要解决问题,可以在构造函数中或在初始化列表中设置成员: Trie() { this->color = 0; this->root = nullptr; } 或: 至于您的代码>颜色< /COD>值,考虑使用元组代替,因为不能保证 int >代码>将是32位整数(假设您需要存储0~255个RGB值): 因为您从未将其设置为nullptr。在color=0;之后的构造函数中,写入root=nullptr;您从未初始化test.root,当您编写test.root==n

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

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

至于您的代码>颜色< /COD>值,考虑使用元组代替,因为不能保证<代码> int >代码>将是32位整数(假设您需要存储0~255个RGB值):


因为您从未将其设置为
nullptr
。在
color=0;
之后的构造函数中,写入
root=nullptr;
您从未初始化
test.root
,当您编写
test.root==nullptr
时,您希望发生什么?因为您的构造函数没有初始化root,所以它可以是任何东西。请注意,white空格是你的朋友。如果没有空格,你的
if
语句很难读懂。如果你认为
int
是32位整数,那你就错了(在某些平台上
int
是16位!)。如果您需要一个32位整数来存储0-255个RGB值的元组,那么您应该使用显式的
uint32\u t
或更好的方法:定义一个包含3个
uint8\u t
值的元组结构。您还可以获得更好的性能,因为成员将与处理器字对齐。
Trie() :
    color ( 0 ),
    root  ( nullptr )
{    
}
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 ) {
    }
}