C ++为POD对象赋值

所以我读到了普通旧数据类(POD) ,并决定让我的结构POD来保存数据。 例如,我有

struct MyClass { int ID; int age; double height; char[8] Name; }; 

显然,要为结构赋值,我可以这样做:

 MyClass.ID = 1; MyClass.age = 20; ... 

但是,无论如何都要分配原始数据,而不知道每个字段的名称?

例如,我的程序检索每列的字段值,并且我想将值赋给结构,因为我不知道字段的名称。

 MyClass c; while (MoreColumns()) { doSomething( c , GetNextColumn() ); //GetNextColumn() returns some value of POD types } 

我假设有使用memcpy或std :: copy的方法,但不知道如何开始..

对不起,如果问题有点不清楚。

您可以使用聚合初始化:

 MyClass c1 = { 1, 20, 6.0, "Bob" }; MyClass c2; c2 = MyClass{ 2, 22, 5.5, "Alice" }; 

循环结构或类的成员没有通用的方法。 添加数据和函数以模拟这类事情有一些技巧,但除了声明类型之外,它们都需要额外的设置工作。

由于MyClass是一个聚合,因此您可以使用大括号初始化程序来初始化一个调用中的所有字段,而无需命名任何字段:

  MyClass m { 1, 2, 42.0, { "Joseph" } }; 

但是,根据您的描述,可能POD不是一个好主意,您可能希望设计一个具有访问器的类来基于(例如)索引列设置内部字段。

也许boost :: fusion可以帮助您存档。
您可以使用adapt宏来迭代结构。 从boost的例子来看:

 struct MyClass { int ID; int age; double height; }; BOOST_FUSION_ADAPT_STRUCT( MyClass, (int, ID) (int, age) (double, height) ) void fillData(int& i) { i = 0; } void fillData(double& d) { d = 99; } struct MoreColumns { template void operator()(T& t) const { fillData(t); } }; int main() { struct MyClass m = { 33, 5, 2.0 }; std::cout << m.ID << std::endl; std::cout << m.age << std::endl; std::cout << m.height << std::endl; MoreColumns c; boost::fusion::for_each(m, c); std::cout << m.ID << std::endl; std::cout << m.age << std::endl; std::cout << m.height << std::endl; } 

您要实现的目标通常会导致难以阅读甚至无法读取的代码。 但是,假设您确实有充分的理由尝试原始数据分配 (而不是初始化)而不知道其名称,则可以使用reinterpret_cast(如下所示)。 我不推荐它,但只想指出你有选择权。

 #include  #include  struct Target { // This is your "target" char foo[8]; }; struct Trap { // The "trap" which lets you manipulate your target // without addressing its internals directly. // Assuming here that an unsigned occupies 4 bytes (not always holds) unsigned i1, i2; }; int main() { Target t; strcpy(t.foo, "AAAAAAA"); // Ask the compiler to "reinterpet" Target* as Trap* Trap* tr = reinterpret_cast(&t); fprintf(stdout, "Before: %s\n", t.foo); printf("%x %x\n", tr->i1, tr->i2); // Now manipulate as you please // Note the byte ordering issue in i2. // on another architecture, you might have to use 0x42424200 tr->i1 = 0x42424242; tr->i2 = 0x00424242; printf("After: %s\n", t.foo); return 0; } 

这只是我提出的一个简单例子,你可以弄清楚如何使它“整洁”。 请注意,在上面,您也可以通过使用“Trap”中的数组而不是i1,i2迭代访问目标,如上所述。

让我重申一下,我不推荐这种风格,但如果你绝对必须这样做,这是你可以探索的一个选项。