作者ric2k1 (Ric)
看板EE_DSnP
标题Re: [讨论] 神奇的()
时间Tue Dec 23 22:54:39 2008
: 今天下午,经过了郝柏翔以及陈韦翰的一起讨论,我们发现了惊人的事实:
:
: 请先看看以下的code: (不要怀疑 它是可以compile的)
:
: 1 #include <iostream>
: 2 using namespace std;
: 3
: 4 int main (int argc, char const* argv[])
: 5 {
: 6 int y(int a=10);
: 7 y();
: 8 int t();
: 9 t();
: 10 return 0;
: 11 }
: 12
: 13 int t(){
: 14 int y(int a=0);
: 15 cout << "In t():";
: 16 y();
: 17 }
: 18
: 19 int y(int x){
: 20 cout << "In y():" << x << endl;
: 21 }
:
: 大家请先猜一猜执行结果?
:
这种写法蛮机车的... XD
:
:
: Ans :
: In y():10
: In t():In y():0
:
: 基本上这个情况大大颠覆了我们(至少是我啦)对function prototype的认知,由测试(nm)
: 可以知道,function prototype在编译之後是不存在的,基本上只是帮助compile认知呼
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
是的, 这点大家要搞清楚有些东西是 for compiler only, 又如 ref var
: 叫function是否正确的工具,因此在不同的scope可以有重复的宣告(还可以有不同的
: default value)。(基本上,全域还会屏蔽function内的,要用::y() access)
这个我倒是没想过, 原来也不知道... 蛮有趣的发现 (笔记ing)
:
: 这是我对这个问题的认知,如果不对的话请多多指教。
: ※ 编辑: ggegge 来自: 124.11.65.12 (12/23 22:10)
: 推 johnathan717:这就是为什麽即使有default value,还是不能宣告 12/23 22:12
: → johnathan717:IntArray a(); 因为这会被当成一个函数的prototype 12/23 22:13
嗯嗯, 这两个 () 的意义是不一样的....
IntArray a; // OK! Calling IntArray()
IntArray a(); // Becomes function prototype
IntArray *a = new IntArray; // OK! Calling IntArray()
IntArray *a = new IntArray(); // OK! Calling IntArray()
也许把 2 & 4 搞混了?
: → johnathan717:参数是void,return type是IntArray 12/23 22:16
: → johnathan717:晚一点陈韦翰应该会来po华丽版的code 12/23 22:17
: → johnathan717:感谢两位同学帮我研究了一个下午XD 12/23 22:18
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.224.40.32
※ 编辑: ric2k1 来自: 61.224.40.32 (12/23 22:55)