我不确定我什至需要使用哪些搜索词来找到该问题的答案,因此,如果重复出现该问题,恕我抱歉。基本上,为什么要编译?
struct A {
A(){};
A(const char*){};
};
int main() {
//const char* b = "what is going on?";
A(b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但这不是吗?
struct A {
A(){};
A(const char*){};
};
int main() {
const char* b = "what is going on?";
A(b);
return 0;
}
test.cpp: In function ‘int main()’:
test.cpp:8: error: conflicting declaration ‘A b’
test.cpp:7: error: ‘b’ has a previous declaration as ‘const char* b’
Run Code Online (Sandbox Code Playgroud)
C ++的什么功能导致这种歧义?这样做的主要目的是在类型A的堆栈上创建一个匿名变量。类似于A a(b);,但未命名a。
这是由C ++语法中的歧义引起的。A(b);被解析为b类型的对象的定义A。[stmt.ambig]中描述了此确切问题。
要解决此问题,请使用统一初始化A{b};或将其用括号括起来以强制将其用作表达式而非声明(A(b));。任一修复都将允许您的程序进行编译。