在C++赋值语句中,等号(=)和大括号({})之间有什么(微妙的?)区别?

mwkjh3gx  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(241)
#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;
}

两者有何不同含义:Token {ch};Token = ch;此错误意味着什么?

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.

使用大括号(Token {ch};)时无错误:

$ c++ -std=c++11 -o poc_Token_assignments poc_Token_assignments.cpp
$   (COMPILED PERFECTLY USING THOSE {} CURLY BRACES)
3j86kqsm

3j86kqsm1#

很简单,看这三行:

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

现在看看您的代码:
Token {ch}与第一行类似,创建了一个Token,然后立即销毁。
Token = ch与第二行类似:不能为类型赋值。
我认为你想要的是其中之一:

Token t = ch;
Token t{ch};
Token t(ch);

对于两者之间的差异,最后我会向你介绍:What are the advantages of list initialization (using curly braces)?或者可能更好;一本好书

相关问题