为什么匿名对象有时需要一个默认构造函数? [英] Why do anonymous objects sometimes require a default constructor?

查看:138
本文介绍了为什么匿名对象有时需要一个默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写下面的程序,它的工作原理如下:

  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()'


在IDEONE上可以看到完整的错误。



第二个程序而不是第一个程序发生错误

解决方案

您已声明一个变量 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(); }

printtest






你想要的是使用统一初始化语法 Foo {x}

  struct Foo {
Foo(std :: string x) {std :: cout< x < std :: endl; }
};

std :: string x(hello,world);

int main(){Foo {x}; }

printhello,world


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(); }

print "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}; }

print "hello, world"

这篇关于为什么匿名对象有时需要一个默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆