2014-10-20 156 views
1
struct A{ 
    A(){} 
}; 

struct B{ 
    B(const A& a){} 
}; 

int main() 
{ 
//Originally I would like to write down below code 

A a; 
B b(a); 

//Unfortunately I end up with below code by accident and there is no compile error 
//I have figured out the below does not create temporary A and call B constructor to 
//create B as the above codes, 
//it declares a function with return value B, name b, 
//and some input parameter, my question is 1) what the input parameter is ? 
//2) How to implement such a function. 

B b(A()); // There is no global function A() in my test case. 

} 

问题是在评论中,我希望有人能帮助我理解它。非常感谢你。声明一个具有类构造函数作为函数参数的函数

+3

相关:[最令人烦恼的解析](http://en.wikipedia.org/wiki/Most_vexing_parse)。 – dasblinkenlight 2014-10-20 21:33:02

回答

3

它声明了一个名为b的函数,它返回B,它具有A (*)()类型的单个参数,即指向不带参数的函数的指针并返回A。声明者A()的意思是“不带参数的函数并返回A”,但是无论何时声明具有函数类型的参数,它都会被重写为函数指针。此声明中的参数未命名(如果不想为参数指定名称,则不需要)。

实施这样的功能,你需要一个定义,例如,

B b(A a()) { 
    // do something with "a" 
    // note: the type of "a" is still pointer to function 
} 

见,例如,Is there any use for local function declarations?

+0

非常感谢您的帮助。我明白了。还有一个问题是为什么A()可以扩展为A(*)()。我不明白这一点。 – 2014-10-20 21:50:07

+0

@ZhongkunMa'A()'表示函数返回'A'(不带参数),'A(*)()'表示指向函数返回'A'(不带参数)的指针。这只是一个规则,如果你试图声明一个函数的参数是一个函数,那么参数的类型会被调整为相应的函数指针类型。 – Brian 2014-10-20 21:55:56

+0

再次感谢您的快速响应。我测试了一件事,如果我宣布“B b”函数为 'B b(A(a)(),A(* b)(),A(*)(),A());' “返回A”函数为 'A returnA(){return A()};' 什么原因可以称为b函数为b(returnA,returnA,returnA,returnA,)'看来'b(A (a)(),A(* b)(),A(*)(),A())'都是完全相同的,对吗?我期待着您的回复。 – 2014-10-20 22:06:19

2

B b(A())声明了一个名为b的函数,它返回B并将函数指针作为参数。函数指针指向一个返回A并且不带参数的函数。

+0

函数的名称是什么?以及如何实现这个功能?谢谢 – 2014-10-20 21:38:19

+0

@ZhongkunMa由于这是**函数'b'的**声明,因此不需要任何参数名称,也不需要在此给出。如果你想实现这个功能,那么你将被要求提供一个带有**定义**的名字。 – 2014-10-20 21:39:38

相关问题