我不确定你叫什么,但我要做的是首先记录在不同时间实例化的三个相同类型的小部件的内存地址。
要识别每个小部件我想要使用我为每个实例记录的内存位置,例如0x .......等,以便再次找到小部件并识别该小部件的特征。
我只是不知道如何使用内存位置并通过将其分配给指针来引用该内存位置?有谁知道怎么做?
我在int。
的向量中记录内存位置vector<int> myvector;
// to show that I have recorded three memory addresses I print them out as integers.
for(int i = 0; i < myvector.size(); i++)
{
cout << myvector[i] <<endl;
}
// then I want to use their location to identify characteristics of each widget.
for(int i = 0; i < myvector.size(); i++)
{
Widget_Type *tpe = myvector[i];
// now identify the x and y value of each widget.
cout << "x value is: " << tpe->x() << endl;
cout << "y value is: " << tpe->y() << endl;
//thats it?
}
答案 0 :(得分:2)
正如评论中已经指出的那样,将指针存储为整数变量是一个坏主意。
只需使用WidgetType*
作为矢量值类型。
您的代码如下所示:
// use WidgetType* instead of int
vector<WidgetType*> myvector;
// print out the pointer values == memory addresses of the pointer
for(int i = 0; i < myvector.size(); i++)
{
cout << myvector[i] <<endl;
}
// access your widgets with your stored pointers
for(int i = 0; i < myvector.size(); i++)
{
cout << "x value is: " << myvector[i]->x() << endl;
cout << "y value is: " << myvector[i]->y() << endl;
}
//that's it