我是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();
Run Code Online (Sandbox Code Playgroud)
在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;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在比较函数中调用strcmp时,我不断得到"对象具有与成员不兼容的类型限定符".我知道我可以删除函数声明中的const,它会消失,但我仍然不明白为什么它首先显示出来.
非常感谢帮助.
您需要const为getter 添加限定符const char* getFamily() const;.这样,可以在const Phone &传递给函数的类型的对象上调用这些getter .
也other.getName应该是other.getName().