作者ric2k1 (Ric)
看板EE_DSnP
標題[情報] Functional Object (for HW1.2.p3b)
時間Fri Sep 30 14:01:35 2011
(幾個禮拜後會教,但我想應該要先提示一下,大家比較知道怎麼寫)
注意: 題目中的 Less, Greater 不是 functions, 而是 class 的名字哦!!
當你宣告一個 class Less, 然後 overload "()" 這個 operator 時,
你就可以把這個 class 的 object 當作是 functional object 來使用。
在進一步說明之前,請大家區分清楚底下 "()" 的意義:
class A
{
public:
A() { ... }
A(int i) { ... }
bool operator() () const { ... }
int operator() (int i) { ... }
};
int f(const A& a)
{
if (a()) // 把 a 當作是 functional object,然後呼叫 bool A::operator() ()
return a(10); // 把 a 當作是 functional object
else
return a(20); // 把 a 當作是 functional object
}
int main()
{
A a(10); // 呼叫 A's constructor
A a = A(10); // 也是呼叫 A's constructor,產生 object 之後 assign 給 a
if (a()) { ... } // 呼叫 bool A::operator() ()
if (A()) { ... } // Error!! 呼叫的是 A's constructor,
// 產生的 object 不能直接給 if 做判斷!!
if (A()()) { ... } // OK, 先呼叫了 A's constructor, 再呼叫 operator()
int k = a(20); // 呼叫 int A::operator(int) ()
f(A()); // 呼叫 A's constructor,產生 object 之後傳給 f() 當參數
// 這就是 functional object
f(A); // Error!! 不能只是傳 class name!!
f(a()); // Error!! 要的是 const A&, 不是 bool!!
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.21.240
1F:推 djshen:謝謝老師的解釋 剛剛應該是其他地方寫錯 所以傳Less()才有 09/30 14:19
2F:→ djshen:問題 09/30 14:19
3F:→ ric2k1:對了,關於 inherit class, 要注意是否所有 functions 都有 09/30 15:03
4F:→ ric2k1:被定義。更精確地說,如果是 pure virtual function, 09/30 15:05
5F:→ ric2k1:則所有的 inherit classes 都要 implement 這個 functions 09/30 15:06
6F:推 gamerred:想問A a = A(10);的constructor呼叫是不是建立兩個物件 09/30 18:36
7F:→ gamerred:再用memberwise assignment? 我的理解中implicit建構似乎 09/30 18:37
8F:→ gamerred:與用explicit呼叫效果只有微妙的差異 而不是在上面那種說 09/30 18:38
9F:→ gamerred:法 是這樣嗎? 09/30 18:38
10F:推 djshen:所以constructor會回傳一個object沒錯吧? 以前計程一直強調 09/30 19:05
11F:→ djshen:寫constructor不可以寫回傳型態 所以沒思考到這點 09/30 19:05
12F:推 gamerred:回大鈞:應該說是呼叫constructor建構新物件 09/30 23:04
13F:→ gamerred:而不是constructor回傳新物件 這種說法比較正確吧 09/30 23:05
14F:→ ric2k1:回 gamerred:是的,嚴格來說 A a = A(10) 的確只是直接 10/01 00:10
15F:→ ric2k1:呼叫個 constructor A(10) 去 construct a, 並不會先產生個 10/01 00:12
16F:→ ric2k1:空的 a 再把 A(10) assign 過去。但我覺得這只是 compiler 10/01 00:13
17F:→ ric2k1:的 optimization, 觀念上兩種說法其實都合理,應該是沒有 10/01 00:14
18F:→ ric2k1:太去在意 (寫程式的時候) 10/01 00:15
19F:→ ric2k1:^-- 必要 10/01 00:15
20F:推 nfprzkuma:感謝老師的精確解說 以前計程沒學過這東西 10/08 16:37