[英]int count{0}. Can I initialize a variable using curly braces in C++?
I am in first year in BSc Computer Science.我在 BSc 计算机科学专业的第一年。 I received a comment from my Professor on my recently submitted assignment .
我收到了教授对我最近提交的作业的评论。 I initialized an int variable to zero :
int count{0};
我将一个 int 变量初始化为零:
int count{0};
. . The book assigned to us in the course gives only one way to initialize a variable by using an assignment statement.
课程中分配给我们的书只提供了一种使用赋值语句来初始化变量的方法。 int count = 0;
整数计数 = 0;
I don't remember where I learnt the curly braces method to initialize the variable.我不记得我在哪里学习了花括号方法来初始化变量。 According to my professor , this is not a legal way to do it.
根据我的教授的说法,这不是合法的方式。 My program runs without any errors in Atom and also on online debugger.
我的程序在 Atom 和在线调试器上运行没有任何错误。 I always check my program for errors from two different platforms.
我总是检查我的程序是否有来自两个不同平台的错误。 So, I am confused whether my method was wrong and was missed by the compiler or this method is legal but not considered standard.
所以,我很困惑我的方法是错误的并且被编译器遗漏了,还是这个方法是合法的但不被认为是标准的。
Any clarification will be helpful.任何澄清都会有所帮助。 Also any advice on good programming practices for debugging, so it doesn't happen again as I lost 4 marks from a 10 mark assignment.
还有关于调试的良好编程实践的任何建议,所以它不会再次发生,因为我从 10 分的作业中失去了 4 分。
Here is how you may initialize the variable count of the type int with zero以下是如何将 int 类型的变量计数初始化为零
int count = 0;
int count = { 0 };
int count = ( 0 );
int count{ 0 };
int count( 0 );
int count = {};
int count{};
You may not write你可能不会写
int count();
because this will be a function declaration.因为这将是一个函数声明。
If to use the specifier auto
then these declarations如果使用说明符
auto
那么这些声明
auto count = { 0 };
auto count = {};
must be excluded from the above list because in this case in the first declaration the variable count will have the type std::initializer_list<int>
and in the second declaration the type of the variable can not be deduced.必须从上面的列表中排除,因为在这种情况下,在第一个声明中,变量 count 将具有
std::initializer_list<int>
类型,而在第二个声明中,变量的类型无法推断。
Pay attention to that the initialization of scalar objects with a braced list was introduced in C++ 11.请注意,使用花括号列表初始化标量对象是在 C++ 11 中引入的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.