c – 为什么匿名对象有时需要默认构造函数?
发布时间:2020-12-16 10:44:12 所属栏目:百科 来源:网络整理
导读:如果我编写以下程序,它可以正常工作: 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::e
如果我编写以下程序,它可以正常工作:
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); } 错误是:
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(); } print “test” 你想要的是使用统一初始化语法Foo {x} struct Foo { Foo (std::string x) { std::cout << x << std::endl; } }; std::string x("hello,world"); int main () { Foo{x}; } print “hello,world” (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |