Convenient C++ struct initialisation(方便的 C++ 结构初始化)
问题描述
我正在尝试找到一种方便的方法来初始化pod"C++ 结构.现在,考虑以下结构:
I'm trying to find a convenient way to initialise 'pod' C++ structs. Now, consider the following struct:
struct FooBar {
int foo;
float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;
如果我想在 C (!) 中方便地初始化它,我可以简单地写:
If I want to conveniently initialise this in C (!), I could simply write:
/* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C
请注意,我想明确避免使用以下符号,因为如果我将来更改结构中的任何内容,我觉得它会折断我的脖子:
Note that I want to explicitly avoid the following notation, because it strikes me as being made to break my neck if I change anything in the struct in the future:
/* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style?
要在 C++ 中实现与 /* A */
示例中相同(或至少相似)的效果,我必须实现一个烦人的构造函数:
To achieve the same (or at least similar) in C++ as in the /* A */
example, I would have to implement an annoying constructor:
FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {}
// ->
/* C */ FooBar fb(12, 3.4);
感觉多余和不必要的.此外,它几乎与 /* B */
示例一样糟糕,因为它没有明确说明哪个值属于哪个成员.
Which feels redundant and unnecessary. Also, it is pretty much as bad as the /* B */
example, as it does not explicitly state which value goes to which member.
所以,我的问题基本上是如何在 C++ 中实现类似于 /* A */
或更好的东西?或者,我可以解释为什么我不应该这样做(即为什么我的心理范式很糟糕).
So, my question is basically how I can achieve something similar to /* A */
or better in C++?
Alternatively, I would be okay with an explanation why I should not want to do this (i.e. why my mental paradigm is bad).
编辑
通过方便,我的意思是也可维护和非冗余.
By convenient, I mean also maintainable and non-redundant.
推荐答案
C++2a 将支持指定的初始化,但您不必等待,因为它们是 官方支持 GCC、Clang 和 MSVC.
Designated initializes will be supported in c++2a, but you don't have to wait, because they are officialy supported by GCC, Clang and MSVC.
#include <iostream>
#include <filesystem>
struct hello_world {
const char* hello;
const char* world;
};
int main ()
{
hello_world hw = {
.hello = "hello, ",
.world = "world!"
};
std::cout << hw.hello << hw.world << std::endl;
return 0;
}
GCC 演示MSVC 演示
正如 @Code Doggo 所指出的,任何使用 Visual Studio 2019 的人都需要为C++ 语言标准"设置 /std:c++latest
Configuration Properties -> 下包含的字段C/C++ ->语言
.
As @Code Doggo noted, anyone who is using Visual Studio 2019 will need to set /std:c++latest
for the "C++ Language Standard" field contained under Configuration Properties -> C/C++ -> Language
.
这篇关于方便的 C++ 结构初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:方便的 C++ 结构初始化
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01