使用初始化器列表初始化包含const数组的结构体

编程入门 行业动态 更新时间:2024-10-27 09:34:45
本文介绍了使用初始化器列表初始化包含const数组的结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用C ++ 11并且有一个包含以下结构的类:

struct设置{ const std :: string name; const std :: string * A; const size_t a; }; class X { static const设置s; //更多的东西};

在 .cpp 像这样定义

X :: s = {MyName,{one,two,three },3};

但这不起作用。但它使用中间变量工作

const std :: string inter [] = {one,two 三}; X :: s = {MyName,inter,3};有没有办法没有中间变量?

div class =h2_lin>解决方案

指针不能从值列表中初始化。您可以改用 std :: vector :

#include<向量> struct设置{ const std :: string name; const std :: vector< std :: string>一个; // ^^^^^^^^^^^^^^^ const size_t a; };

然后您可以写:

class X { static const Settings s; //更多的东西}; const设置X :: s = {MyName,{one,two,three},3}

这里是 。

如Praetorian在建议中所建议,您可能需要替换 std ::向量与 std :: array ,如果您可以明确指定容器的大小,如果大小不需要在运行时更改:

#include< array> struct设置{ const std :: string name; const std :: array< std :: string,3>一个; // ^^^^^^^^^^^^^^^^^ const size_t a; };

这里是 生活示例 。

I working with C++11 and have a Class containing the following Struct:

struct Settings{ const std::string name; const std::string* A; const size_t a; }; class X { static const Settings s; //More stuff };

In the .cpp file I want to define it like this

X::s = {"MyName", {"one","two","three"}, 3};

But this does not work. However it does work using an intermediate variable

const std::string inter[] = {"one","two","three"}; X::s = {"MyName", inter, 3};

Is there a way to do it without the intermediate variable?

解决方案

A pointer cannot be initialized from a list of values. You could use std::vector instead:

#include <vector> struct Settings{ const std::string name; const std::vector<std::string> A; // ^^^^^^^^^^^^^^^^^^^^^^^^ const size_t a; };

You can then write:

class X { static const Settings s; //More stuff }; const Settings X::s = {"MyName", {"one","two","three"}, 3};

Here is a live example.

As suggested by Praetorian in the comments, you may want to replace std::vector with std::array, if it is acceptable for you to specify the size of the container explicitly, and if the size does not need to change at run-time:

#include <array> struct Settings{ const std::string name; const std::array<std::string, 3> A; // ^^^^^^^^^^^^^^^^^^^^^^^^^^ const size_t a; };

And here is the live example.

更多推荐

使用初始化器列表初始化包含const数组的结构体

本文发布于:2023-07-30 11:08:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1248856.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   数组   结构   列表   const

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!