【问题标题】:Function Pointer declarations [duplicate]函数指针声明 [重复]
【发布时间】: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


【解决方案1】:

为什么会这样?

规则来自 C,在 C++ 中它的工作原理相同。来自函数参数列表内的c++标准dcl.fct

...确定每个参数的类型后,将任何类型为“T的数组”或函数类型T的参数调整为“指向T的指针”。 ...

在函数参数列表中,函数类型为integer() 的参数被转换为指向该类型integer(*)() 的指针。

那么 integer() 实际上等于 integer(*)() 吗?

在函数参数列表里面,是的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    相关资源
    最近更新 更多