有什么办法可以使用int变量来完成组件名称?

时间:2020-05-18 15:59:31

标签: c++ c++builder

例如,我可以使用int变量x = 5来获取组件编号5,Image1,Image2 ... Image5。

就像您在数组中使用变量来选择数组array [x]的特定元素一样。

3 个答案:

答案 0 :(得分:1)

不是直接 ,否。意思是,这样的事情不起作用:

int x = 5;
Imagex->...

或者:

int x = 5;
(Image + x)->...

如其他答案所述,您可以将组件指针存储到一个数组中,然后根据需要使用该变量将其索引到该数组中,例如:

TImage* Images[5];
...
Images[0] = Image1;
Images[1] = Image2;
Images[2] = Image3;
Images[3] = Image4;
Images[4] = Image5;
...
int x = 5;
Images[x-1]->...

还有另一种选择-您可以使用组件所有者的FindComponent()方法(对于设计时放置的任何组件,其中TFormOwner),例如:

int x = 5;
static_cast<TImage*>(Owner->FindComponent("Image"+String(x)))->...

然后,可以通过在循环中使用FindComponent()来避免对引用进行硬编码,从而与数组方法结合使用:

TImage* Images[5];
...
for(int num = 1; i <= 5; ++num)
    Images[num-1] = static_cast<TImage*>(Owner->FindComponent("Image"+String(num)));
...
int x = 5;
Images[x-1]->...

答案 1 :(得分:0)

您可以使用向量保持,假设图像,然后仔细使用自定义函数按索引获取图像,您需要了解的技巧是,如果以某种方式对向量进行排序或任何元素更改其位置,则您的代码将被破坏...

这里是一个例子。

#include <vector>

std::vector<abc::file> files {file1,file2,file3,file4};
abc::file getByIndex(int index)
{
    if(index<0 || index>files.size())
        return abc::file::invalid;
    return files.at(index);
}

int main()
{
    int i = 5; 
    abc::file5 = getByIndex(i);
    std::cout << 'here is the end\n';
}

答案 2 :(得分:0)

有什么方法可以使用int变量来完成组件名称吗?

否。

但是,也没有必要因为:

您可以在数组中使用变量来选择数组array [x]的特定元素。

结论:您可以改用数组。