指针未在C 类中初始化
pointer not initialized in c++ class
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 ) {
}
}
相关文章:
- 分段错误 - 读取初始化指针的数组
- 初始化指针的常量向量
- 初始化指针或引用成员变量以指向另一个成员
- C++初始化指针/引用/复制细微差别
- 使用无效指针初始化指针声明符的行为是否未定义?
- 在一行中初始化指针(新uint8_t[高度*宽度*3])
- 如何使用可变模板初始化指针?
- 初始化指针时出现写入访问冲突
- C 错误,带有卷曲括号的字面初始化指针
- 重新初始化指针是一种不好的做法吗?
- 初始化指针?C
- 初始化指针向量的向量
- 如何在类函数中正确初始化指针
- C++初始化指针会使应用程序随机崩溃
- 初始化指针结构 - 内存中的外观
- 如何使用struct构造函数在结构中初始化指针阵列
- 在一行中声明并初始化指针到类实例
- 分配数组与初始化指针
- QT 中的非初始化指针
- 使用地址值初始化指针