Comparison with Null in C ++

Ok, please carefully inspect my code below, its just part of the function

void RepeatWord(){ system("cls"); string word = NULL; string newword = NULL; int repeats = 0; while(true){ if(word == NULL){ cout<<"Currently no word is stored.."; cout<<"\n\nPlease enter a word: "; cin>>word; } .... 

I have worked with other programming languages, and I always do a comparison with a NULL value, but in C ++ ... it seems this is a different situation. The error says.

error: no match for 'operator ==' in 'word == 0'

Well, I was wondering what I'm just comparing with NULL , and I really don't know why this is wrong. Comparing values ​​with NULL with C ++ is different? please teach me. Thanks

Note: I know more rubies than java

+4
source share
2 answers

You are trying to compare an object with NULL , you cannot compare objects with NULL . You need to compare the pointer. In doing so, you check to see if the pointer indicates that it is not a valid object.

In your case, you want to check if std::string empty. You can use the member functions provided by std::string , std::string::empty() .

Given your questions, I emphasize the need for a good study book:

The ultimate guide and list of books in C ++

+7
source

If you come from the Java world, you really will find that this object in C ++ is not processed the same way. In C ++, unless explicitly stated, data is processed directly. In Java, an object is completely controlled by a virtual machine, and because of this it makes sense to allow programs to access them only by reference. Therefore, whenever you write a Java program, you must instruct the virtual machine to host the object with new and until you assign null class instance variable. Following the same principle, if you assign an object variable to another, both will refer to the same object, and a method call on both will call this method in the same base instance.

In C ++, there are two different mechanisms for getting the same result:

  • using pointers whose syntax for type T is

     T *t; 

    so std::string *word; will define a variable named word by holding the pointer to std::string .

  • using the link:

     T &t; 

In C ++, both of these types are types, i.e. std::string , std::string * , std::string & are three different types. The first of them really means the structured value itself, while the other two indicate an indirect relation to a value of type std::string .

The difference between these types of indications is explained by this SO entry.

In your code, you will either have to replace all null occurrences with an empty string literal "" , or use pointers and select instances using the new operator before trying to use the object, for example, in the string cin >> word; .

+2
source

All Articles