c++ - 为什么匿名对象有时需要默认构造函数?

标签 c++ most-vexing-parse

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

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

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"

关于c++ - 为什么匿名对象有时需要默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24622472/

相关文章:

c++ - 案例 'p' 的问题 || 'P' : syntax within a switch statement in C++

c++ - 为什么我不能像这样淡化 std::array?

c++ - 即使 nm 报告存在符号,运行时也会出现符号查找错误

c++ - 使用模板模板参数作为类函数的返回类型

c++ - 构造函数不抛出异常

C++ 诡异的构造函数

c++ - 函数指针声明

c++ - 运算符计算方向

c++ - 带空括号的默认构造函数

C++: 奇怪的 "Request for member X of Y which is of non-class type Z"