【发布时间】:2013-09-07 04:35:54
【问题描述】:
我对下面的代码很困惑:
class Tree {
protected:
struct Node {
Node* leftSibling;
Node* rightSibling;
int value;
};
private:
Node* root;
int value;
.....
public:
void addElement(int number) {
if (root == NULL) {
printf("This is the value of the pointer %lld\n",(long long)root);
printf("This is the value of the int %d\n",value);
...
return;
}
printf("NOT NULL\n");
}
};
int main() {
Tree curTree;
srand(time(0));
for(int i = 0;i < 40; ++i) {
curTree.addElement(rand() % 1000);
}
}
curTree 变量是主函数的本地变量,所以我希望它的成员不会初始化为 0,但它们都已初始化。
【问题讨论】:
-
类是否有用户定义的默认构造函数?
-
您本质上是在问为什么会这样吗?
if (root == NULL)以及为什么 root 最终会为空? -
您正在打印的
value是addElement的参数,而不是私有成员。使用this->value打印属性。 -
没有用户定义的构造函数。我在问为什么要初始化这些值,因为我认为它们不应该如此。感谢 agbinfo 指出我遇到的那个非常愚蠢的错误。
-
@user502248:零是未初始化的有效值。
标签: c++ variable-initialization