【发布时间】:2012-11-23 07:23:12
【问题描述】:
对成员引用和指针运算符的功能有些担忧..
举个例子:
struct ID{
uint8_t index;
bool active;
}
struct Square{
struct ID shortID;
struct BUDDY *bud;
uint8_t x;
uint8_t y;
};
然后我稍后返回一个指向正方形的指针.. 我的问题是:然后我可以修改 ID 的成员并将更改反映在嵌套结构中吗?
void function1()
{
Square *someSquare = GetSquare(1);
someSquare->shortID.index = 89; // Is this now reflected everywhere? OR was the shortID struct only modified in the scope of this funciton..
}
void function2()
{
Square *someSquare = GetSquare(1);
if ( someSquare->shortID.index != 89 )
{
// Dang...
}
}
谢谢!
编辑:
感谢您的简洁回答,是的,GetSquare 函数返回一个指向正方形数组的指定索引的指针。像这样:
Square* GetSquare( uint8_t index )
{
return &squares[index];
}
所以实例每次都应该相同,因为“squares”数组在对象创建时分配一次。所以感谢您的洞察力,我的问题必须在我的代码中的其他地方:)
【问题讨论】:
-
这完全取决于
GetSquare的作用。它是每次返回不同的实例,还是相同的实例? -
-1 请复制并粘贴真实代码。对于上面的伪装代码,至少修复缩进并添加必要的分号。你让人们猜测!
标签: c++ c pointers nested chaining