簡體   English   中英

C ++ const”,並且對象具有與成員不兼容的類型限定符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM