我正在与C2751 https://msdn.microsoft.com/en-us/library/7w01cz7z.aspx编译器错误,不太明白到底是什么原因导致的。下面的小代码会产生错误:
#include <iostream>
class A {
public:
A () { std::cout << "A constructed" << std::endl; };
static A giveA () { return A (); }
};
class B {
public:
B (const A& a) { std::cout << "B constructed" << std::endl; }
};
int main () {
B b1 = B (A::giveA ()); // works
B b2 (B (A::giveA ())); // C2751
B b3 (A::giveA ()); // works
}
编译器输出:
consoleapplication1.cpp(21): error C2751: 'A::giveA': the name of a function parameter cannot be qualified
为什么我不能显式调用构造函数b2
?
这是问题的最麻烦的解析 https://en.wikipedia.org/wiki/Most_vexing_parse。在 clang 下编译会给出完整的诊断:
<source>:18:17: error: parameter declarator cannot be qualified
B b2 (B (A::giveA ())); // C2751
~~~^
<source>:18:10: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
B b2 (B (A::giveA ())); // C2751
^~~~~~~~~~~~~~~~~
<source>:18:11: note: add a pair of parentheses to declare a variable
B b2 (B (A::giveA ())); // C2751
^
( )
1 warning and 1 error generated.
Compiler exited with result code 1
按照编译器的建议进行修复:
B b2 ((B (A::giveA ()))); // no error
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)