Why do anonymous objects sometimes require a default constructor?

三世轮回 提交于 2019-12-02 00:58:46

问题


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?


回答1:


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"




回答2:


Foo(x); means the same as Foo x; . You can add redundant parentheses to the name of the variable.

So you need the default constructor because this is creating a variable x with no arguments being passed to constructor.

You can workaround this by doing Foo{x}; in C++11.

The parsing rule is that if something could be a valid declaration and a valid non-declaration statement, then it is in fact a declaration. See also most vexing parse




回答3:


I completely agree with above solution. Though this will still work:

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


int main () 
{ 
    string x = "hello, world";
    Foo * abc = new Foo(x); 
    return 0;
}


来源:https://stackoverflow.com/questions/24622472/why-do-anonymous-objects-sometimes-require-a-default-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!