[問題] 關於friend函數的使用問題

看板C_and_CPP (C/C++)作者 (Hypnus)時間15年前 (2011/04/27 11:43), 編輯推噓4(407)
留言11則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux 問題(Question): 以下程式碼會在main()中產生:'Count' was not declared in this scope 請問這樣使用上有什麼錯誤嗎? 程式碼(Code):(請善用置底文網頁, 記得排版) 程式碼片段如下: Test.h: class Test{ public: Test(double a, double b) { part1 = a; part2 = b; } friend Test Count(const double a, const double b); private: double part1; double part2; }; Test.cpp: #include "Test.h" Test Count(const double a, const double b) { return Test(a+b, a-b); } main.cpp: #include "Test.h" int main() { cout << Count(9.7, 3.22) << endl; return 0; } 先謝謝各位 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.33.201.221

04/27 12:37, , 1F
編譯器很明確的給你錯誤訊息了.........
04/27 12:37, 1F

04/27 12:37, , 2F
不然你覺得他cout 要印甚麼東西出來?
04/27 12:37, 2F

04/27 12:38, , 3F
Count的呼叫方式不正確
04/27 12:38, 3F

04/27 12:39, , 4F
Test Test::Count(..) 也不正確
04/27 12:39, 4F

04/27 12:41, , 5F
你是不是想要用static ...
04/27 12:41, 5F

04/27 13:23, , 6F
沒有count可以呼叫 你的Test.cpp 那個東西不會被摳到
04/27 13:23, 6F

04/27 13:29, , 7F
重點在於friend function 不是屬於Test這個class的
04/27 13:29, 7F

04/27 13:29, , 8F
如果include Test.cpp 就會對了
04/27 13:29, 8F

04/27 13:47, , 9F
樓上那樣改不好,應該要在Test.h加入Count函數的宣告
04/27 13:47, 9F

04/27 13:47, , 10F
而不是去include cpp
04/27 13:47, 10F

04/27 13:51, , 11F
yap! 還有要記得overload <<
04/27 13:51, 11F
sorry,本來想把原本程式碼改成簡化結果改壞了... 基本上忽略掉cout的不合理,singlovesong大講到我問題的重點了 問題已經解決,感謝singlovesong和iamstudent兩位的解答~ ※ 編輯: Hypnus 來自: 114.33.201.221 (04/27 14:06)
文章代碼(AID): #1Djv3Nbl (C_and_CPP)
文章代碼(AID): #1Djv3Nbl (C_and_CPP)