我试图从struct BlockA的构造函数中访问对象regA和对象regB的成员。我希望能够从构造函数中分配给BlockA的地址为BlockA对象的每个regtype成员分配一个递增的地址。我希望分配给regtype成员的地址根据其大小递增。
现在,我让我的构造函数尝试为字符串分配地址,这不起作用,对吧?我也有错误说在MemberAddress函数中,regA和regB是未定义的。
有没有办法让编译器将MemberAddress函数返回的字符串识别为BlockA中定义的成员的地址?指出你看到的其他问题也将不胜感激。
struct RegTypeA {
int addr ;
int val ;
};
struct RegTypeB {
int addr ;
int val ;
};
struct BlockA {
RegTypeA regA ;
RegTypeB regB ;
int addr;
BlockA(int address);
};
size_t BLOCK_STRUCT_MEMBERS_TypeSize(const unsigned int idx) {
static const size_t sizes[] = { sizeof(RegTypeA), sizeof(RegTypeB), };
if (idx < (sizeof(sizes)/sizeof(sizes[0]))) return sizes[idx];
return 0;
};
const char* BLOCK_STRUCT_MEMBERS_MemberAddress(const unsigned int idx) {
static const char * names[] = { regA.addr, regB.addr };
if (idx < (sizeof(names)/sizeof(names[0]))) return names[idx];
return "UNKNOWN";
};
BlockA::BlockA(int address) {
addr = address;
const int y = 1 +1 +1;
for (int i = 0; i < y; i++) {
size_t size = BLOCK_STRUCT_MEMBERS_TypeSize(i);
std::string regaddress = BLOCK_STRUCT_MEMBERS_MemberAddress(i);
regaddress = address;
address = address + size;
std::cout << address;
}
}
int main()
{
BlockA blockA1(3);
std::cout << blockA1.regA.addr << std::endl << blockA1.regB.addr;
std::cin.get();
return 0;
}
答案 0 :(得分:0)
我想你想要:
BlockA::BlockA(int address) :
addr(address)
{
regA.addr = address; // regA.addr = address + offsetof(BlockA, regA)
regB.addr = address + sizeof(regA); // regB.addr = address + offsetof(BlockA, regB)
}