某年,阿里巴巴出了如下笔试题一枚:
- struct Foo{
- Foo(){}
- Foo(int){}
- void fun(){}
- };
- int main()
- {
- // printf("Hello world!\n");
- Foo a(10);
- a.fun();
- Foo b();
- b.fun();
- return 0;
- }
问题:上面程序中,那个语句是错误的。
如果直接编译,会在第12行报错。code::block编译器报出如下错误信息:
error: request for member 'fun' in 'b', which is of non-class type 'Foo()'
从错误信息中可以看出来,编译器发现在b里面需要一个非类类型Foo的成员fun。
改正:第11行改为Foo b;
说明:默认构造函数式没有任何参数的构造函数,如果使用Foo b();有的编译器会解释成一个返回类型是Foo的函数b。