[英]The object has type qualifiers that are not compatible with the member function C++
[英]C++ const "and the object has type qualifiers that are not compatible with the member
我是C ++编程的新手,在我的OPP课中,我们被要求创建电话簿。
现在,在讲座中,教授讲了一些关于如果您要确保注入到方法中的变量不会被更改的事情,您必须在其上加上const。
到目前为止,这是我的代码。
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();
并在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;
}
当我尝试在我的compare函数中调用strcmp时,我不断收到“对象具有与成员不兼容的类型限定符”。 我知道我只需要在函数声明中删除const,它就会消失,但是我仍然不明白为什么它首先显示。
帮助将不胜感激。
您需要为getter添加const
限定符const char* getFamily() const;
。 这样,可以在传递给函数的const Phone &
类型的对象上调用这些getter。
另外other.getName
应该是other.getName()
。
除了可以正确建议const
限定您的getter的其他答案之外,您还可以直接访问other
的数据成员,从而避免了这些调用。
int Phone::compare(const Phone & other) const
{
int result = strcmp(family, other.family);
if (result == 0) {
result = strcmp(name, other.name);
}
return result;
}
你的签名
int Phone::compare(const Phone & other) const
意味着在该功能内部,您需要确保不更改Phone
实例。
目前,您的函数调用了const char* getFamily()
(和getName
,您错过了()
调用)。 这些函数都不是const
,因此是错误的。
如果您也将它们标记为const,那就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.