简体   繁体   中英

C++ const "and the object has type qualifiers that are not compatible with the member

I'm new to C++ programming and in my OPP class we were requested to create a phone book.

Now, in the lecture the Professor said something about that if you want to make sure that your variable that is being injected to a method doesn't get changed you must put const on it.

here is my code so far.

private:
 static int phoneCount;
 char* name;
 char* family;
 int phone;
 Phone* nextPhone;

public:
    int compare(const Phone&other) const;
    const char* getFamily();
    const char* getName();

and in Phone.cpp

int Phone::compare(const Phone & other) const
{
 int result = 0;
 result = strcmp(this->family, other.getFamily());
 if (result == 0) {
    result = strcmp(this->name, other.getName);
 }
 return 0;
}

I keep getting "the object has type qualifiers that are not compatible with the member" when I try to call to strcmp inside my compare function. I know that I can just remove the const in the function declaration and it will go away, but I still doesn't understand why it's showing in the first place.

Help would be greatly appreciated.

You need to add const qualifier for getters const char* getFamily() const; . This way these getters can be invoked on objects of type const Phone & that you pass into function.

Also other.getName should be other.getName() .

In addition to the other answers that correctly suggest const qualifying your getters, you can access the data members of other directly, avoiding those calls.

int Phone::compare(const Phone & other) const
{
 int result = strcmp(family, other.family);
 if (result == 0) {
    result = strcmp(name, other.name);
 }
 return result;
}

Your signature

int Phone::compare(const Phone & other) const

means inside that function you need to ensure you don't change the Phone instance.

At the moment, your function calls const char* getFamily() (and getName , which you've missed the () call from). Neither of these functions are const , hence the error.

If you mark these as const too, it will be ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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