c++ - 在 C++ 中使用内存位置字符串

标签 c++ pointers widget

我不确定你怎么调用它,但我想做的是首先记录在不同时间实例化的三个相同类型的小部件的内存地址。

为了识别每个小部件,我想使用我为每个实例记录的内存位置,例如 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/

相关文章:

c++ - 返回带槽的数据

pointers - UnsafeMutablePointer<Int8> 来自 Swift 中的字符串

c - 从 64 位机器中的 C 函数访问返回地址时出现段错误

android - 小部件出现在小部件预览中但不在 Android 4 的小部件列表中

c++ - Qt 在布局中自动排列小部件

c++ - 这个动态分配有什么作用?

c++ - 是否可以在 X86 处理器上自动加载和存储?

C:当从数组引用时,我的结构的属性不会改变?

Flutter 连接节点/小部件图

c++ - 测试 QQuickView (QWindow) 在 Qt 5.0.x 中是否全屏