简体   繁体   English

C ++ 0x指定的初始化程序

[英]C++0x Designated Initializers

I could find a way to do Designated Initializers in C++0x with only one member initializing. 我可以找到一种方法,仅用一个成员进行初始化即可在C ++ 0x中进行。 Is there a way for multiple member initializing ? 有多个成员初始化的方法吗?

public struct Point3D
{
    Point3D(float x,y) : X_(x) {}
    float X;
};

I want : 我想要 :

public struct Point3D
{
    Point3D(float x,y,z) : X_(x), Y_(y), Z_(z) {}
    float X_,Y_,Z_;
};

You have a few mistakes in your constructor, here is how you should write it: 您的构造函数中有一些错误,这是您应该如何编写的:

/* public */ struct Point3D
// ^^^^^^ 
// Remove this if you are writing native C++ code!
{
    Point3D(float x, float y, float z) : X_(x), Y_(y), Z_(z) {}
    //               ^^^^^    ^^^^^
    //               You should specify a type for each argument individually
    float X_;
    float Y_;
    float Z_;
};

Notice, that the public keyword in native C++ has a meaning which is different from the one you probably expect. 请注意,本机C ++中的public关键字的含义与您可能期望的含义不同。 Just remove that. 删除它。

Moreover, initialization lists (what you mistakenly call "Designated Initializers") are not a new feature of C++11, they have always been present in C++. 此外, 初始化列表 (您误称为“指定的初始化程序”)不是C ++ 11的新功能,它们始终存在于C ++中。

@Andy explained how you should be doing this if you're going to define your own struct . @Andy解释了如果要定义自己的struct时应该如何做。

However, there is an alternative: 但是,还有一种替代方法:

#include <tuple>

typedef std::tuple<float, float, float> Point3D;

and then define some function as: 然后定义一些函数为:

//non-const version
float& x(Point3D & p) { return std::get<0>(p); }
float& y(Point3D & p) { return std::get<1>(p); }
float& z(Point3D & p) { return std::get<2>(p); }

//const-version
float const& x(Point3D const & p) { return std::get<0>(p); }
float const& y(Point3D const & p) { return std::get<1>(p); }
float const& z(Point3D const & p) { return std::get<2>(p); }

Done! 完成!

Now you would use it as: 现在,您可以将其用作:

Point3D p {1,2,3};
x(p) = 10; // changing the x component of p!
z(p) = 10; // changing the z component of p!

Means instead of px , you write x(p) . 意思是用x(p)代替px

Hope that gives you some starting point as to how to reuse existing code. 希望这为您提供有关如何重用现有代码的起点。

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

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