我不确定你怎么调用它,但我想做的是首先记录在不同时间实例化的三个相同类型的小部件的内存地址。
为了识别每个小部件,我想使用我为每个实例记录的内存位置,例如 0x...... 等,再次找到小部件并识别该小部件的特征。
我只是不知道如何使用内存位置并通过将其分配给指针来引用该内存位置?有人知道怎么做吗?
我将内存位置记录在一个 int vector 中。
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?
}
最佳答案
正如评论中已经指出的那样,将指针存储为整型变量不是一个好主意。
只需使用 WidgetType*
作为 vector 值类型。
你的代码看起来像这样:
// 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
关于c++ - 在 C++ 中使用内存位置字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30525351/