Re: [ROOT] To create sortable objects and add them to a TSortedList

From: Vincent ROBERFROID (roberfroid@fynu.ucl.ac.be)
Date: Mon Nov 17 2003 - 13:21:49 MET


Hello Jose,

for the warnings, try to define the i variable "public" and not "private".
Else you cannot use ((MyClass*)obj)->i.

You typed

>    MyClass *obj1 = new MyClass(4);
>    MyClass *obj2 = new MyClass(2);
>    MyClass *obj3 = new MyClass(6); 

in your code. So, the output is 4, 2, 6.
Why do you expect 2, 4, 6 ?

Vincent

On Monday 17 November 2003 11:39, Jose Caballero wrote:
> Hello:
>
>
> I am trying to create a class and then to add the objects in a
> TSortedList. My class is:
>
> *************************************
>
> class MyClass : public TObject {
> private:
>    Int_t i;
> public:
>    MyClass(int x = 0) : i(x) {}
>    ~MyClass(){}
>    void Set(int x) { i=x; }
>    Int_t Get() const { return i;}
>    Bool_t IsEqual (TObject *obj) const
>    {
>       return i == ((MyClass*)obj)->i;
>    }
>    Int_t Compare(TObject *obj) const
>    {
>       if ( i <  ((MyClass*)obj)->i ) return -1;
>       if ( i == ((MyClass*)obj)->i ) return 0;
>       if ( i >  ((MyClass*)obj)->i ) return 1;
>    }
>    Bool_t IsSortable() const { return kTRUE; }
>    ULong_t Hash() const { return i; }
>
>    ClassDef(MyClass,1);
> };
>
> *************************************
>
> My code is:
>
>    TSortedList *list = new TSortedList;
>    MyClass *obj1 = new MyClass(4);
>    MyClass *obj2 = new MyClass(2);
>    MyClass *obj3 = new MyClass(6);
>
>    list->Add(obj1);
>    list->Add(obj2);
>    list->Add(obj3);
>
>
>    for ( Int_t i=0; i<3; i++) {
>       cout << ( (MyClass *)list->At(i) )->Get() << endl;
>    }
>
> *************************************
>
>
> When I compile the program, ROOT returns:
>
> /root/include/TObject.h:110: warning: `virtual Int_t
>    TObject::Compare(const TObject*) const' was hidden
> MyClass.p.h:14: warning:   by `
>    Int_t MyClass::Compare(TObject*) const'
> /root/include/TObject.h:136: warning: `virtual Bool_t
>    TObject::IsEqual(const TObject*) const' was hidden
> MyClass.h:10: warning:   by `
>    Bool_t MyClass::IsEqual(TObject*) const'
>
>
> And when I execute the code, I obtain:
>
> Warning in <MyClass::Compare>: this method must be overridden!
> Warning in <MyClass::Compare>: this method must be overridden!
> Warning in <MyClass::Compare>: this method must be overridden!
> 4
> 2
> 6
>
>
> But I expected
> 2
> 4
> 6
>
>
> What am I doing incorrectly?
> What must I do to obtain 2 4 6?
>
> Thank you very much in advance for your help.
> Best regards. Jose.



This archive was generated by hypermail 2b29 : Thu Jan 01 2004 - 17:50:16 MET