简体   繁体   English

与NULL相关的C ++指针

[英]C++ Pointer relating to NULL

I'm new to c++ and i have a question about the following code below. 我是C ++的新手,我对以下代码有疑问。 Is it true that the line " if(p1.spouse || p2.spouse) return false " is another way saying " if(p1.spouse!= NULL || p2.spouse!=NULL)return false " ? 这是真的,行“ 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;
}

Yes, it is true. 是的,它是真的。 Any pointer in boolean context evaluates to false if it is NULL and to true if it is not NULL. 布尔上下文中的任何指针如果为NULL,则求值为false;如果不为NULL,则求值为true。

Many people consider it poor style, and prefer to do the explicit comparison != NULL . 许多人认为它的风格很差,更喜欢进行显式比较!= NULL

Personally I find it quite elegant: it means existence of the object. 我个人觉得它很优雅:这意味着该对象的存在。 Particularly with short-circuit boolean && : 特别是对于短路布尔&&

if (obj && ojb->whatever())
    ...;

That is true, and this is very often used feature. 是的,这是非常常用的功能。

from : http://en.cppreference.com/w/cpp/language/implicit_cast 来自: http : //en.cppreference.com/w/cpp/language/implicit_cast

"The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true. " “值零(用于整数,浮点和无作用域枚举),并且空指针和空指针成员值变为false。所有其他值变为true。”

you can find a lot more implicit conversion rules at that url 您可以在该网址找到更多隐式转换规则

Yes you're right. 你是对的。 Any pointer ,if NULL, returns false if used in conditional expression. 如果在条件表达式中使用任何指针(如果为NULL),则返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM