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