3

如果我编写以下程序,它会按我的预期工作:

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

错误是:

prog.cc: In function 'int main()':
prog.cc:10:20: error: no matching function for call to 'Foo::Foo()'

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

为什么第二个程序而不是第一个程序会出现错误?

4

3 回答 3

12

你已经声明了一个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}; }

打印“你好,世界”

于 2014-07-08T01:50:04.227 回答
8

Foo(x);意思相同Foo x;。您可以在变量名称中添加多余的括号。

所以你需要默认构造函数,因为这是创建一个x没有参数传递给构造函数的变量。

您可以通过Foo{x};在 C++11 中解决此问题。

解析规则是,如果某事可以是有效的声明和有效的非声明语句,那么它实际上是一个声明。另请参阅最令人烦恼的解析

于 2014-07-08T01:49:00.823 回答
-1

我完全同意上述解决方案。虽然这仍然有效:

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


int main () 
{ 
    string x = "hello, world";
    Foo * abc = new Foo(x); 
    return 0;
}
于 2014-07-08T03:06:43.790 回答