如果指针设置为 NULL,则对它的任何引用或通过它的引用也不会为 NULL。这是一个可编译的示例,当您尝试运行它时会爆炸:
#include <string>
#include <iostream>
#define NULL 0
class Seedcoat {
public:
//Seedcoat();
std::string Name;
int Weight;
};
class Seed {
public:
//Seed();
std::string Name;
int Weight;
Seedcoat* ItsSeedcoat;
};
class Apple {
public:
//Apple();
std::string Name;
int Weight;
Seed* ItsSeed;
};
int main()
{
///////Apple Objects Begin///////
Apple MyApple;
Seed MySeed;
Seedcoat MySeedCoat;
MyApple.ItsSeed = &MySeed;
MyApple.ItsSeed->ItsSeedcoat = &MySeedCoat;
MyApple.ItsSeed->ItsSeedcoat->Weight = 2;
if ( MyApple.ItsSeed != NULL) {
std::cout << "The weight of the apple seed's seedcoat is " << MyApple.ItsSeed->ItsSeedcoat->Weight <<".\n";
}
MyApple.ItsSeed = NULL;
if ( MyApple.ItsSeed->ItsSeedcoat != NULL) {
std::cout << "The weight of the apple seed's seedcoat is " << MyApple.ItsSeed->ItsSeedcoat->Weight <<".\n";
}
return 0;
}
所以我的问题是:为什么会这样
MyApple.ItsSeed->ItsSeedcoat != NULL
返回真。我认为它不会因为 ItsSeed 设置为 NULL - 但它仍然尝试引用 ItsSeedcoat 的权重值 - 然后我认为它会爆炸,因为 ItsSeed 不存在。我意识到有一些简单的方法可以解决这个问题——这个例子只是为了展示我正在观察的行为。这有什么好担心的吗?- 或者这是正常行为?这样做的原因是什么?谢谢。