簡體   English   中英

Qt- Qlist檢查包含Custom類

[英]Qt- Qlist checking contains with Custom class

有沒有辦法覆蓋加載自定義類的Qt QList的比較機制。

即在java中你只需要覆蓋一個比較方法。

我正在使用我的customclass模型的QList。

QList <CustomClass *>list;
CustomClass *c1=new CustomClass();
c1.name= "john";
list.append(c2); 
CustomClass *c2=new CustomClass();
c2.name= "john";

qDebug()<<list.contains(c2);  //false

//Secondly I have overridden the equals '==' operator and still getting false
qDebug()<< (c1 == c2); //false, why ? 
qDebug()<< (c1->operator ==(*c2)); //true

class CustomClass
{
QString name;
 bool operator==(const CustomClass& other)const
{
    if(this->name==(other.name))
    {
        return true;
    }
    return false;
}
}

這一行:

qDebug()<< (c1 == c2); //false, why ? 

它是false因為你不是在比較實際的實例,而是指針。

試試這個:

qDebug()<< (*c1 == *c2);

對於第一個問題,您需要存儲實際對象,而不僅僅是指向它們的指針。 為了能夠將對象存儲在Qt容器(如QList ,該類必須具有以下內容:

  • 默認構造函數
  • 復制構造函數
  • 賦值運算符

在這種情況下,編譯器隱式生成的構造函數和賦值運算符就足夠了。 如果您的班級有指針成員,您需要明確的復制/分配來涵蓋所有權問題。

對於QList::contains()您可以像現在一樣重載operator==()

對於第二個問題,@ Joachim Pileborg是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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