[英]C++ Pointer relating to NULL
我是C ++的新手,我对以下代码有疑问。 这是真的,行“ if(p1.spouse || p2.spouse) return false
”是另一种方式说: “ if(p1.spouse!= NULL || p2.spouse!=NULL)return false
”?
struct Person
{
string name;
string bday;
int height;
Person* spouse;
};
bool marry(Person&, Person&);
int main()
{
Person john;
john.name = "John";
john.bday = "May 29, 1917";
john.height = 72;
john.spouse = NULL;
Person marilyn;
marilyn.name = "Marilyn";
marilyn.bday = "06/01/1926";
marilyn.height = 64;
marilyn.spouse = NULL;
marry(john, marilyn);
cout << "John is married to " << john.spouse->name << endl;
}
bool marry(Person& p1, Person& p2)
{
if (p1.spouse || p2.spouse) return false;
p1.spouse = &p2;
p2.spouse = &p1;
return true;
}
是的,它是真的。 布尔上下文中的任何指针如果为NULL,则求值为false;如果不为NULL,则求值为true。
许多人认为它的风格很差,更喜欢进行显式比较!= NULL
。
我个人觉得它很优雅:这意味着该对象的存在。 特别是对于短路布尔&&
:
if (obj && ojb->whatever())
...;
是的,这是非常常用的功能。
来自: http : //en.cppreference.com/w/cpp/language/implicit_cast
“值零(用于整数,浮点和无作用域枚举),并且空指针和空指针成员值变为false。所有其他值变为true。”
您可以在该网址找到更多隐式转换规则
你是对的。 如果在条件表达式中使用任何指针(如果为NULL),则返回false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.