为什么匿名对象有时需要一个默认构造函数? [英] Why do anonymous objects sometimes require a default constructor?
本文介绍了为什么匿名对象有时需要一个默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我写下面的程序,它的工作原理如下:
struct Foo {
Foo :: 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:在函数'int main()':
prog.cc:10:20:error :没有匹配函数调用'Foo :: Foo()'
第二个程序而不是第一个程序发生错误
解决方案您已声明一个变量 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(); }
你想要的是使用统一初始化语法 Foo {x}
struct Foo {
Foo(std :: string x) {std :: cout< x < std :: endl; }
};
std :: string x(hello,world);
int main(){Foo {x}; }
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}; }
这篇关于为什么匿名对象有时需要一个默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文