有什么区别
typedef void (&FunctionTypeR)();
对比
typedef void (FunctionType)();
第二个也是函数的引用吗? FunctionTypeR
用作参数类型时是否等同于 FunctionType&
?
为了
void foo(FunctionType bar)
当调用 foo 时,运行时是否复制参数 bar(一个函数)?
最佳答案
区别在于你不能创建函数类型的对象,但是你可以创建函数指针类型的对象,以及函数引用类型。
这意味着如果你有一个函数,将 f()
说成:
void f(){}
下面是你能做什么,不能做什么:
FunctionType fun1 = f; //error - cannot create object of function type
FunctionType *fun2 = f; //ok
FunctionTypeR fun3 = f; //ok
测试代码:
typedef void (&FunctionTypeR)();
typedef void FunctionType();
void f(){}
int main() {
FunctionType fun1 = f; //error - cannot create object of function type
FunctionType *fun2 = f; //ok
FunctionTypeR fun3 = f; //ok
return 0;
}
现在看到编译错误(和警告):
prog.cpp: In function ‘int main()’:
prog.cpp:7: error: function ‘void fun1()’ is initialized like a variable
prog.cpp:8: warning: unused variable ‘fun2’
prog.cpp:9: warning: unused variable ‘fun3’
但是,如果您在函数参数列表中使用 FunctionType
(这是一个函数类型):
void foo(FunctionType bar);
那么就相当于
void foo(FunctionType * bar);
这意味着,无论你写什么,你都可以使用 bar
调用函数:
bar(); //ok
(*bar)(); //ok
也就是说,你可以这样写:
void h(FunctionType fun) { fun(); }
void g(FunctionType fun) { (*fun)(); }
这是由于函数类型到函数指针类型的调整;也就是说,函数类型被调整成为一个指向函数类型的指针:
Function type | Function pointer type (adjusted type)
void () | void (*)()
void (int) | void (*)(int)
int (int,int) | int (*)(int,int)
.... | ... so on
C++03 标准在 §13.1/3 中说,
Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5).
[Example:
void h(int());
void h(int (*)()); // redeclaration of h(int())
void h(int x()) { } // definition of h(int())
void h(int (*x)()) { } // ill-formed: redefinition of h(int())
]
如果您使用 `FunctionTypeR
(这是一个函数 reference 类型)作为:
void foo(FunctionTypeR bar);
那么它相当于:
void foo(FunctionType * & bar);
还有,
void h(FunctionTypeR fun) { fun(); }
void g(FunctionTypeR fun) { (*fun)(); }
有趣的部分...
您可以使用 FunctionType 来声明一个函数(但不能定义它)。
例如,
struct A
{
//member function declaration.
FunctionType f; //equivalent to : void f();
};
void A::f() //definition
{
std::cout << "haha" << std::endl;
}
//forward declaration
FunctionType h; //equivalent to : void h();
int main() {
A a;
a.f(); //call member function
h(); //call non-member function
}
void h() //definition goes below main()
{
std::cout <<"hmmm.." << std::endl;
}
关于c++ - 函数语法引用 - 带和不带 &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7321993/