If I write the following program, it works as I expect:
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
int main () { Foo("hello, world"); }
However, if I write a slightly different program, I get a compilation error:
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
std::string x("hello, world");
int main () { Foo(x); }
The error is:
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.
Why does the error occur for the second program and not the first?
You have declared a variable x
with type 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(); }
What you want is use uniform initialization syntax Foo{x}
struct Foo {
Foo (std::string x) { std::cout << x << std::endl; }
};
std::string x("hello, world");
int main () { Foo{x}; }