[英]What is the (subtle?) difference between equal (=) and curly braces ({}) on C++ assignments?
#include "std_lib_facilities.h"
class Token {
public:
char kind;
double value;
string name;
Token ( char ch ) : kind{ch} { }
Token ( char ch, double val ) : kind {ch}, value {val} { }
Token ( char ch, string n ) : kind {ch}, name {n} { }
};
int main ( void )
{
char ch;
cin >> ch;
// Token == ch; // Fails to compile - see below.
Token {ch};
return 0;
}
What is the different meaning between: Token {ch};
Token {ch};
之间的不同含义是什么? versus Token = ch;
与
Token = ch;
What does this error means?这个错误是什么意思?
error: expected unqualified-id
ERROR WHEN USING `Token = ch;`.
$ c++ -std=c++11 -o poc_Token_assignments poc_Token_assignments.cpp
poc_Token_assignments.cpp:20:8: error: expected unqualified-id
`Token = ch;`
^
1 error generated.
Non-error when using curly braces ( Token {ch};
):使用花括号(
Token {ch};
)时不报错:
$ c++ -std=c++11 -o poc_Token_assignments poc_Token_assignments.cpp
$ (COMPILED PERFECTLY USING THOSE {} CURLY BRACES)
It is pretty simple, look at these three lines:很简单,看这三行:
5; // Creates an int literal which goes away right away
int = 5; // Syntax error: Cannot assign a value to a type
int a = 5; // Correct: Store the value 5 in the variable a
Now for your code:现在为您的代码:
Token {ch}
is similar to the first line. Token {ch}
类似于第一行。 A Token
is created and then destroyed right away. Token
被创建,然后立即被销毁。
Token = ch
similar to the second line: You cannot assign a value to a type. Token = ch
类似第二行:不能给类型赋值。
What I think you want is one of these:我想你想要的是其中之一:
Token t = ch;
Token t{ch};
Token t(ch);
For the difference between the two last I will refer you to: What are the advantages of list initialization (using curly braces)?最后两者的区别可以参考: List initialization (using curly braces)有什么好处? or perhaps better;
或者更好; a good book.
一本好书。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.