c++ - 通过指针分配给类内的数据

标签 c++

假设我们有这样一个类型:

struct MyType
{
  OtherType* m_pfirst;
  OtherType* m_psecond;
  OtherType* m_pthird;

  ....
  OtherType* m_pn;
};

分配给其成员是否是一种安全的方式?

MyType inst;
....
OtherType** pOther = &inst.m_pfirst;

for (int i = 0; i < numOfFields; ++i, ++pOther)
{
   *pOther = getAddr(i);
}

最佳答案

如果您的字段以这种方式命名,那么您别无选择:

inst.m_pFirst = getaddr(0);
inst.m_pSecond = getaddr(1);
...

更好的结构可能是:

struct MyType {
    OtherType *m_pFields[10];
}

...
for (int i=0; i<10; i++) {
    inst.m_pFields[i] = getaddr(i);
}

在标记 C++ 时,您可以使用构造函数:

struct MyType {
    OtherType *m_pFirst;
    OtherType *m_pSecond;
    MyType(OtherType *p1,OtherType *p2): m_pFirst(p1), m_pSecond(p2) {};
};
...
MyType inst(getaddr(0),getaddr(1));

关于c++ - 通过指针分配给类内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34900194/

相关文章:

c++ - 如何在C++中匹配两个不同的图像

c++ - `boost::xtime_get` 是否已弃用?

c++ - 设置对话框窗口类名

c++ - 在没有 UTC 时区的正确时间总和

c++ - Nlohmann json 获取类型推导

c++ - 使用 SIMD 去交错半字节 vector

C++ 风格 : Prefixing virtual keyword to overridden methods

c++ - 在完成端口调用 WSASend()?

c++ - 为什么我不能将函数分配给函数指针?

c++ - 如何分解 vector 并将其值用作函数的参数?