首页 > 解决方案 > 无法从“TFmxChildrenList”转换为“TRectangle *”

问题描述

我是使用 C++ Builder 的新手,如果我犯了任何基本错误,我深表歉意。

我绘制了一个名为“Collection”的 TLayout,其中包含一个 5x5 的 TRectangle 网格。细胞被命名为“CellXY”。我认为在表单上绘制这些内容可能比用代码实例化它们更容易,现在我不这么想,但我仍然想以这种方式解决问题以更好地理解。

我正在尝试编写一个方法,该方法将返回一个指向 TRectangle 的指针,其名称包含传递给该方法的坐标。

目前,我正试图通过迭代 TLayout 集合的孩子来做到这一点:

TRectangle* __fastcall TForm2::getCellRectangleFromCoordinate(int X, int Y){
    TRectangle* targetCell = NULL;
    char targetCellName[6];
    sprintf(targetCellName, "Cell%i%i", X, Y);
    for (int cIndex = 0; cIndex < Collection->ChildrenCount; ++cIndex)
    {
        TRectangle* cellRect = (TRectangle*) Collection->Children[cIndex]; // Error Here
        string cellName = cellRect->Name;
        if (targetCellName == cellName) {
            targetCell = cellRect;
            break;
        }
    }
    return targetCell;
}

但我得到一个错误阅读:

E2031 Cannot cast from 'TFmxChildrenList' to 'TRectangle *'

如果有人可以提供帮助,我将不胜感激!

标签: c++builderc++builder-10.2-tokyo

解决方案


Children属性是一个指向TFmxChildrenList内部保存对象数组的类类型 ( ) 的指针。 Children不是实际的数组本身,就像您试图将其视为一样。

Children[cIndex]正在使用指针算术,这不是您在这种情况下想要的。您需要Children->Items[]通过更改以下语句来使用子属性:

Collection->Children[cIndex]

对此:

Collection->Children->Items[cIndex]

或这个:

(*(Collection->Children))[cIndex]

推荐阅读