一个头文件中初始化定制结构的向量 [英] Initialize a vector of customizable structs within an header file

查看:186
本文介绍了一个头文件中初始化定制结构的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法让全球结构的列表,并初始化包含它们的修改版本来自同一头文件中的向量?
我知道我不能直接从h文件访问和编辑的变量,因为它不是运行时code,但也许有恰好是一个解决方法这一点 - 也许,我只是碰巧一些很基本的方式跳过对C ++初学者手册..如果是的话请原谅!

Is there any way to have a list of global structs and initialize a vector containing modified version of them from within the same header file? I know I can't directly access and edit variables from an .h file, since it's not run-time code, but maybe there happens to be a workaround to this - or maybe some very basic way that I just happened to skip on the C++ Beginners manual.. pardon me if so!

要做出一个例子,假设我有一个COM prehends几个成员的结构,并宣布在.h文件中一些全局的人。

To make an example, let's say I have a struct which comprehends a couple of members, and declared some global ones in the .h file..

struct MyStruct
{
  unsigned int a;
  string foo;
  float myfloat;
};

MyStruct struct_one={1,"hello",0.238f};
MyStruct struct_two={10,"salve",3.14f};
MyStruct struct_three={3,"bonjour",0.001f};
MyStruct struct_four={6,"dias",5.0f};

然后我就可以初始化包含它们的这种方式(不知道这是否是最好的一个,虽然)

I can then initialize a vector containing them this way (don't know if it's the best one though)

MyStruct MyStructArray[] = {struct_one, struct_two, struct_three, struct_four};

vector<MyStruct> MyStructVector(MyStructArray,
MyStructArray+sizeof(MyStructArray)/sizeof(MyStructArray[0]));

不过,我想能够改变,对飞,一些结构的成员创造不改变全局对象的向量(或阵列)之前。
可能吗?

But I would like to be able to change, on the fly, some of the structs' members before creating the vector (or the array) without changing the global ones. Possible?

编辑:通过一个头文件中的我的意思是,一个头文件中。如果我做 unsigned int类型A = 100; 在标题中,我没有初始化或拨打东西在实际来源,使其工作。本身矢量完​​美的作品,我只是想知道是否有从原来的全球结构的修改版本构建它的方式..说,我想用相同的全局结构,但对成员不同的值 A

By "within an header file" I meant, "within an header file". If I do unsigned int a = 100; in the header, I don't have to initialize or call something in the actual source to make it work. The vector by itself works perfectly, I only wanted to know if there was a way to build it from modified versions of the original global structs.. say, I want to use the same global structs, but with different values for member a.

推荐答案

在@Sam的回答之上...

On top of @Sam 's answer...

使用构造函数:

struct MyStruct {
    unsigned int a;
    string foo;
    float myfloat;

    MyStruct(unsigned int a, const string& foo, float myfloat) : a(a) , foo(foo), myfloat(myfloat) {}
};

现在你可以用一个简单的声明你的结构添加到载体

Now you can add your struct to the vector with a simple statement

vec.push_back(MyStruct(1, "hello", 0.238f));


class Foo {
public:
    static std::vector<int> MyStructVector;
}

inline std::vector<MyStruct> MakeVector()
{
    std::vector vec;
    vec.push_back(MyStruct(1, "hello", 0.238f));
    //...
    return vec;
}

std::vector<MyStruct> Foo::MyStructVector= MakeVector();

这篇关于一个头文件中初始化定制结构的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆