【发布时间】:2020-04-13 05:56:58
【问题描述】:
前几天我试图通过调用另一个类的默认构造函数来创建一个对象,结果它做了一个函数声明,下面是一个例子:
struct integer {
integer(){} //Default constructor.
};
struct rational {
rational(integer n, integer d){} //Default constructor.
};
void multiply(rational(), rational()) { //Valid syntax? Takes two function pointers.
}
rational one_half() {
return rational(integer(), integer()); //Here doesnt make a function declaration.
}
int main() {
rational num(integer(), integer()); //Here makes a function declaration,
//instead of constructing a rational object.
multiply(one_half, one_half); //function taking two function pointers.
}
为什么会这样?我知道并且可以像 integer::integer() 这样调用构造函数,但我想了解这里发生了什么以及为什么 integer() 在此示例中的行为类似于 integer(*)()。
【问题讨论】:
-
你熟悉most vexing parse吗?
-
@CoryKramer 不,我会检查一下
-
那么
integer()实际上等于integer(*)()吗? -
JaMiT 是的,谢谢
标签: c++ function function-pointers default-constructor most-vexing-parse