【问题标题】:How to assign address of a struct to another struct?如何将结构的地址分配给另一个结构?
【发布时间】:2012-07-29 13:24:03
【问题描述】:

假设我有

struct someStruct
{
    int a;
};

和 2 个类。

在第一类的方法中,我创建了一个结构的实例:

someStruct structName;

现在我想把这个结构的地址传递给另一个类的构造函数

std::auto_ptr<2ndClass> 2ndClass_ (new 2ndClass(structName));

我想在这里使用 2ndClass 中更改的结构值 - 请阅读下文...

第二类有:

标题:

...
class 2ndClass...
... 
private:
someStruct &structName2;
public:
__fastcall 2ndClass(someStruct &structName);
...

cpp:

__fastcall 2ndClass::2ndClass(someStruct &structName)
    : structName2(structName)
{
...

这显然是 structName 的一个副本。

我的问题是:如何从 structName 为 structName2 分配一个地址,以便我可以读取和写入结构,然后在离开第二个类后在第一类中使用这些值?如果不使用指向结构的指针,我该怎么做?

【问题讨论】:

  • 你为什么不想使用指针?

标签: c++ struct object-address


【解决方案1】:

这显然会复制 structName。

不,它没有。您通过引用传递,并且您的成员是一个引用,因此2ndClass::structName2 将引用您作为参数传递给构造函数的确切对象。

问题是如何从 structName 为 structName2 分配地址,以便我可以读取和写入结构,然后在离开第二类后在第一类中使用这些值。

您不需要这样做,因为您使用的是参考资料。在函数签名中,&amp; 代表引用,而不是地址。所以你传递的不是地址,而是对象本身。

注意,如果原始结构超出范围,您将有一个悬空引用,因此请务必处理这种情况。如果内存没有被覆盖,它似乎可以工作,但这是未定义的行为。

【讨论】:

  • @user1566456 请注意,如果原始结构超出范围,您将有一个悬空引用,因此请务必处理这种情况。如果内存没有被覆盖,它可能看起来工作,但这是未定义的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 2013-03-04
  • 1970-01-01
  • 2015-11-06
  • 2018-03-29
  • 1970-01-01
相关资源
最近更新 更多