假设我们有这样一个类型:
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/