如果我编写以下程序,它会按我预期的那样工作:
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
int main () { Foo("hello, world"); }
但是,如果我编写一个稍微不同的程序,我会得到一个编译错误:
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
std::string x("hello, world");
int main () { Foo(x); }
错误是:
prog.cc: In function 'int main()':
prog.cc:10:20: error: no matching function for call to 'Foo::Foo()'
The complete error can be seen on IDEONE.
为什么错误发生在第二个程序而不是第一个?
最佳答案
你已经声明了一个类型为 Foo
的变量 x
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(); }
你想要的是使用统一的初始化语法 Foo{x}
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
std::string x("hello, world");
int main () { Foo{x}; }
关于c++ - 为什么匿名对象有时需要默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24622472/