jxh*_*jxh 3 c++ most-vexing-parse
如果我编写以下程序,它可以正常工作:
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
int main () { Foo("hello, world"); }
Run Code Online (Sandbox Code Playgroud)
但是,如果我编写一个稍微不同的程序,我会收到编译错误:
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
std::string x("hello, world");
int main () { Foo(x); }
Run Code Online (Sandbox Code Playgroud)
错误是:
prog.cc: In function 'int main()':prog.cc:10:20: error: no matching function for call to 'Foo::Foo()'
为什么第二个程序出错而不是第一个出错?
Bry*_*hen 12
您已x使用类型声明了变量Foo
struct Foo {
Foo(){}
Foo (std::string x) { std::cout << x << std::endl; }
void test(){ std::cout << "test" << std::endl; };
};
std::string x("hello, world");
int main () { Foo(x); x.test(); }
Run Code Online (Sandbox Code Playgroud)
你想要的是使用统一初始化语法 Foo{x}
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
std::string x("hello, world");
int main () { Foo{x}; }
Run Code Online (Sandbox Code Playgroud)