这不是lambda函数问题,我知道我可以将lambda赋给变量.
允许我们声明,但不在代码中定义函数是什么意思?
例如:
#include <iostream>
int main()
{
// This is illegal
// int one(int bar) { return 13 + bar; }
// This is legal, but why would I want this?
int two(int bar);
// This gets the job done but man it's complicated
class three{
int m_iBar;
public:
three(int bar):m_iBar(13 + bar){}
operator int(){return m_iBar;}
};
std::cout << three(42) << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以我想知道的是为什么C++会允许two哪些看似无用,three哪个看起来更复杂,但却不允许one?
编辑:
从答案中可以看出,代码内声明可能能够防止命名空间污染,我希望听到的是为什么声明函数的能力已被允许,但是不允许定义函数的能力.
我找到了有趣的东西.错误消息说明了一切.在获取非静态成员函数的地址时不允许使用括号的原因是什么?我在gcc 4.3.4上编译了它.
#include <iostream>
class myfoo{
public:
int foo(int number){
return (number*10);
}
};
int main (int argc, char * const argv[]) {
int (myfoo::*fPtr)(int) = NULL;
fPtr = &(myfoo::foo); // main.cpp:14
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误:main.cpp:14:错误:ISO C++禁止获取非限定或带括号的非静态成员函数的地址,以形成指向成员函数的指针.说'&myfoo :: foo'