[問題] function declaration

看板C_and_CPP作者時間6年前 (2017/12/01 17:25), 6年前編輯推噓5(507)
留言12則, 4人參與, 6年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) g++ 4.8.3 程式碼(Code):(請善用置底文網頁, 記得排版) #include <iostream> #include <typeinfo> using namespace std; int fff =0; class C{ public: C():a(1){ cout <<"GG\n"; fff++;} C(int x){ a=x; cout <<"Orz\n"; } int a; }; int main(int argc, char** argv) { int foo1(int, int), foo2(int g, int k); C c1(),c2(); // compile error -> cout << c1.a << c2.a << endl; cout << fff << endl; C c3(10); int foo3(C()); int foo4(C(C())); return 0; } 問題: 本來在跟同事研究copy elision的問題 弄了半天才知道 C c1(C())這樣寫在main裡面根本就不會有一個叫做c1的物件產生... 而是會被當作function declaration (如上例的compile error) 不過我想問的問題是.. 所以foo3 跟 foo4這樣寫 (compile會過..) 這兩個function吃的參數到底是什麼意思啊Orz (稍微google一下好像是只有GCC能夠特例讓他過0.0 https://bytes.com/topic/c/answers/136234-constructor-function-argument) 是某種function pointer嗎? 我implement 他的時候 應該要怎麼接到這個... C()..? int foo3(C()){ //...? } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1512120348.A.0DF.html

12/01 17:34, 6年前 , 1F
int foo(C())的意思是,宣告一個叫foo的函數,他的回
12/01 17:34, 1F

12/01 17:35, 6年前 , 2F
傳型態是int,吃一個function ptr參數,而此參數是一
12/01 17:35, 2F

12/01 17:35, 6年前 , 3F
個回傳C、不吃任何參數的函數
12/01 17:35, 3F
感謝解答! ※ 編輯: XDucka (114.136.159.112), 12/01/2017 17:44:53

12/01 17:46, 6年前 , 4F
請愛用{}
12/01 17:46, 4F

12/01 20:24, 6年前 , 5F
C c1(C());可以宣告物件啊,只要C有對應的建構子就行
12/01 20:24, 5F

12/01 20:26, 6年前 , 6F
例如補上 C(const C &c){this->a=c.a;} 這樣的建構子
12/01 20:26, 6F

12/01 20:27, 6年前 , 7F
只是沒人會這麼寫就是了
12/01 20:27, 7F

12/01 20:32, 6年前 , 8F
而且沒人會在函式裡做前置宣告的,錯誤實在太多了
12/01 20:32, 8F

12/01 20:47, 6年前 , 9F
我猜樓上那段會踩到most vexing parse,沒試過不確定
12/01 20:47, 9F

12/01 21:19, 6年前 , 10F
most vexing我沒遇過,可能我運氣好一直沒湊齊條件吧
12/01 21:19, 10F

12/02 00:12, 6年前 , 11F
這篇在講的問題就是 MVP, 樓上提的也是同樣的狀況
12/02 00:12, 11F

12/02 00:13, 6年前 , 12F
要閃就是如上面說的請愛用 {} 初始化
12/02 00:13, 12F
文章代碼(AID): #1Q8I0S3V (C_and_CPP)