简体   繁体   English

如何在将POD结构作为变量传递时初始化它?

[英]How to initialize a POD struct while passing it as a variable?

For instance i have a RECT and a some sub that has a RECT as a parameter 例如,我有一个RECT和一个以RECT作为参数的子

RECT wr = {0, 0, somevar1, somevar2};
someSub(wr);

Since i dont need the RECT anywhere else is there a way to initialize it as i send it to the sub? 既然我不需要其他任何地方的RECT有一种方法来初始化它,因为我发送到子? Something like 就像是

someSub(RECT {0, 0, somevar1, somevar2}); <- doesnt work :(

oh ya using vs2010 to compile 哦,你用vs2010编译

What I've did in the past is to create a substruct with a constructor: 我过去所做的是使用构造函数创建子结构:

struct Rect : RECT
{
    Rect(long l, long t, long r, long b)
    {
        left   = l;
        top    = t;
        right  = r;
        bottom = b;
    }
};

someSub(Rect(a, b, c, d));

The Rect itself is not a POD, because it has a constructor, but it will be spliced or downcasted into a RECT (or RECT& ) on passing to the function. Rect本身不是POD,因为它有一个构造函数,但在传递给函数时它将被拼接或下载到RECT (或RECT& )中。

Naturally, if you look at it, it is no different than creating a function: 当然,如果你看一下,它与创建一个函数没什么不同:

RECT Rect(long l, long t, long r, long b)
{
    RECT r = {l, t, r, b};
    return r;
}

It even has the same syntax! 它甚至具有相同的语法! But the constructor thing feels to me somewhat better. 但构造函数对我来说有点好看。

In C++11, you can inline the struct in the call: 在C ++ 11中,您可以在调用中内联结构:

func({0, 0, somevar1, somevar2});

In older versions of C/C++, you can create a helper function that initializes the structure and returns the result: 在旧版本的C / C ++中,您可以创建一个辅助函数来初始化结构并返回结果:

inline RECT new_RECT(int a, int b, int c, int d)
{
    RECT ret = {a, b, c, d};
    return ret;
}

Then you can call: 然后你可以打电话:

func(new_RECT(a, b, c, d));

and the struct creation should be inlined by the compiler. 并且编译器应该内联结构创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM