Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为字符串指定大括号内的初始值设定项时出错_C++_C Strings_Assignment Operator_Initializer - Fatal编程技术网

C++ 为字符串指定大括号内的初始值设定项时出错

C++ 为字符串指定大括号内的初始值设定项时出错,c++,c-strings,assignment-operator,initializer,C++,C Strings,Assignment Operator,Initializer,它在GCC中给出了以下错误: struct A{ char s[10]; }; int main() { A a1; a1 = {"abc"}; return 0; } 函数“int main()”中的: 8:8:错误:“运算符=”不匹配(操作数类型为“A”和“”) 8:8:注:候选人为: 1:8:注意:A&A::operator=(常量A&) 1:8:注意:参数1从“”到“常量A&”的转换未知 1:8:注意:A&A::operator=(

它在GCC中给出了以下错误:

struct A{
    char s[10];

};
int main()
{
    A a1;
    a1 = {"abc"};
    return 0;
}
函数“int main()”中的
:
8:8:错误:“运算符=”不匹配(操作数类型为“A”和“”)
8:8:注:候选人为:
1:8:注意:A&A::operator=(常量A&)
1:8:注意:参数1从“”到“常量A&”的转换未知
1:8:注意:A&A::operator=(A&&)
1:8:注意:参数1没有从“”到“A&&”的已知转换
但在VisualStudio中工作良好(甚至没有警告)。所以我想知道它是特定于编译器的吗?C++标准对此有什么看法吗?对我来说,GCC的行为看起来是正确的。但有人能解释一下这背后的基本原理吗

注意:如果我初始化为
aa1={“abc”}
,那么它在GCC中可以正常工作。那么为什么分配操作不起作用呢

编辑:a1={'a','b','c'}和a1={'abc'}之间有什么区别。前者适用于GCC。

此声明:

 In function 'int main()':
8:8: error: no match for 'operator=' (operand types are 'A' and '<brace-enclosed initializer list>')
8:8: note: candidates are:
1:8: note: A& A::operator=(const A&)
1:8: note:   no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'const A&'
1:8: note: A& A::operator=(A&&)
1:8: note:   no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'A&&'
a = {"abc"};  // error
格式不正确,错误消息非常清楚地说明了原因。语句正在尝试执行赋值,但赋值的左侧是
A
,右侧是大括号init列表。没有接受大括号初始化列表的
A::operator=
,因此赋值不起作用


另一方面,这种说法:

 In function 'int main()':
8:8: error: no match for 'operator=' (operand types are 'A' and '<brace-enclosed initializer list>')
8:8: note: candidates are:
1:8: note: A& A::operator=(const A&)
1:8: note:   no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'const A&'
1:8: note: A& A::operator=(A&&)
1:8: note:   no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'A&&'
a = {"abc"};  // error
正在构造类型为
A
的对象,该对象考虑
A
的所有构造函数。由于
A
是聚合类型,因此有一个构造函数可以接受单个参数,用于初始化
s


这意味着,如果要指定给现有对象,可以创建一个
A
对象,然后指定它:

A a = {"abc"};  // ok

a1={“abc”}不是初始化。这是一项任务<代码>a1={“abc”}是一个初始化。为什么a1={'a','b','c'}可以工作?谢谢@cigien。不知道为什么VS允许这样做。@BlueBird对不起,我不知道。反正我也不经常用msvc编译。