我有这两个类:
class Foo
{
public:
Foo() { std::cout << "in Foo constructor" << std::endl; }
};
class Bar
{
public:
Bar() {};
Bar(Foo foo);
private:
Foo m_foo;
};
Bar::Bar(Foo foo) :
m_foo(foo)
{
std::cout << "in Bar constructor with argument Foo" << std::endl;
}
int main() {
Bar bar(Foo()); // is something wrong here ?
return 0;
}
我编译并执行了它,屏幕上没有打印,Bar bar(Foo())
做了什么?
我在Do the parentheses after the type name make a difference with new?和Foo f = Foo(); // no matching function for call to 'Foo::Foo(Foo)'看到了相似之处,但我仍然无法弄明白。
答案 0 :(得分:1)
为了在不改变语义的情况下实现相同的目的(即not using the copy or assignment constructor),添加括号以消除语法歧义(编译器不知道你是否在本地声明一个函数,或者你是否构建了一个对象,默认情况下是前者按C ++标准划分优先顺序):
int main() {
Bar bar ( (Foo()) );
return 0;
}
正如评论中发布的Wikipedia page所指出的那样,这是C ++语法本身的一个问题,你无能为力。
答案 1 :(得分:0)
确定有人指出compiler thinks that you are declaring a function。通过 Pubby 和 Nbr44 。这是一种如何解决它的方法。只需让编译器知道您正在声明变量。
int main() {
Bar bar = Foo();
return 0;
}