Checking for a null object in C++

后端 未结 8 1079
南旧
南旧 2020-12-13 17:55

I\'ve mostly only worked with C and am running into some unfamiliar issues in C++.

Let\'s say that I have some function like this in C, which would be very typical:<

8条回答
  •  眼角桃花
    2020-12-13 18:22

    You can use a special designated object as the null object in case of references as follows:

    class SomeClass
    {
        public:
    
            int operator==(SomeClass &object)
            {
                if(this == &object) 
                {
                        return true;
                }
    
                return false;
            }
    
    
        static SomeClass NullObject;
    };
    
    SomeClass SomeClass::NullObject;
    
    void print(SomeClass &val)
    {
        if(val == SomeClass::NullObject)
        {
            printf("\nNULL");
        }
        else
        {
            printf("\nNOT NULL");
        }
    }
    

提交回复
热议问题