Borland C++ ListView Error



我不断出现错误:

[bcc32错误]

试图编译时。

我试图用我的TList元素组成的元素填充TListView

void __fastcall TDogReportForm::FormCreate(TObject *Sender)
{
    DogListView->Items->Clear();
    for (int i = 0; i < DogList->Count; i++) {
       TListItem * Item;
       Item = DogListView->Items->Add();
       Item->Caption = DogList->Items[i]->firstName;
       Item->SubItems->Add(DogList->Items[i]->lastName);
       Item->SubItems->Add(DogList->Items[i]->ownerName);
       Item->SubItems->Add(DogList->Items[i]->hours);
       Item->SubItems->Add(DogList->Items[i]->dogNum);
   }
}

每行的错误都包含DogList->

TList持有未型void*指针。其Items[]属性Getter返回void*指针。您需要进行类型铸造以访问数据字段:

// DO NOT use the OnCreate event in C++! Use the actual constructor instead...
__fastcall TDogReportForm::TDogReportForm(TComponent *Owner)
    : TForm(Owner)
{
    DogListView->Items->Clear();
    for (int i = 0; i < DogList->Count; i++)
    {
       // use whatever your real type name is...
       MyDogInfo *Dog = static_cast<MyDogInfo*>(DogList->Items[i]); // <-- type-cast needed!
       TListItem *Item = DogListView->Items->Add();
       Item->Caption = Dog->firstName;
       Item->SubItems->Add(Dog->lastName);
       Item->SubItems->Add(Dog->ownerName);
       Item->SubItems->Add(Dog->hours);
       Item->SubItems->Add(Dog->dogNum);
   }
}

在旁注上,您可以考虑在虚拟模式下使用TListView(将OwnerData设置为true并分配OnData事件处理程序),而不是将所有狗信息复制到TListView,因此可以直接从DogList显示信息需要时按需:

__fastcall TDogReportForm::TDogReportForm(TComponent *Owner)
    : TForm(Owner)
{
    DogListView->Items->Count = DogList->Count;
}
void __fastcall TDogReportForm::DogListViewData(TObject *Sender, TListItem *Item)
{
    // use whatever your real type name is...
    MyDogInfo *Dog = static_cast<MyDogInfo*>(DogList->Items[Item->Index]);
    Item->Caption = Dog->firstName;
    Item->SubItems->Add(Dog->lastName);
    Item->SubItems->Add(Dog->ownerName);
    Item->SubItems->Add(Dog->hours);
    Item->SubItems->Add(Dog->dogNum);
}

话虽如此,您应该更改DogList以使用更像TList的类型安全容器,例如std::vector

std::vector<MyDogInfo> DogList;
...
MyDogInfo &Dog = DogList[index]; // <-- no type-cast needed
Item->Caption = Dog.firstName;
Item->SubItems->Add(Dog.lastName);
Item->SubItems->Add(Dog.ownerName);
Item->SubItems->Add(Dog.hours);
Item->SubItems->Add(Dog.dogNum);

最新更新