[問題] 繼承與多型的問題
※ [本文轉錄自 C_and_CPP 看板]
作者: ytli1204 (YT) 看板: C_and_CPP
標題: [問題] 繼承與多型的問題
時間: Sun Apr 13 16:53:01 2008
現在要設計用於幾何物件之間,計算兩兩相交情形的程式,
由於想要將物件放在一起管理,所以使用繼承同一個 base class
的方式來設計幾何物件,但是在計算相交的函式中,必須
要知道這兩個物件的型別(ex: sphere to sphere),所以我
使用迂迴的方式與重載來推導出物件的型別,但 compiler
會說重載無法找到符合的函式,請問要怎樣寫才會是對的?
或是架構應該要如何修改 @@
--------------------------
以下是我的程式架構..
我有一個 Base class : CGeometry
與兩個Derived class : CSphere and CPoint
兩個幾何物件相交的回傳值是 CIntersection
CGeometry 的定義 ==> http://src.wtgstudio.com/?iw81Uv
CSphere 的定義與實作 ==>
.h http://src.wtgstudio.com/?j3waI3
.cpp http://src.wtgstudio.com/?0HQc58
CPoint 的定義與實作 ==>
.h http://src.wtgstudio.com/?mqOS4R
.cpp http://src.wtgstudio.com/?od5tJd
CIntersection 的定義 ==> http://src.wtgstudio.com/?iPfY4P
將全部的東西放在一起管理成 GeometryLib.h
http://src.wtgstudio.com/?U52442
這是我測試用的 main.cpp ==> http://src.wtgstudio.com/?5d0gI0
vc2003下的整個 project
http://0rz.tw/7c3TC
------------------------------------------------
測試結果 ==> http://0rz.tw/ff3TO
由測試可以知道在非多型的情況下可以進入正確的 intersection 函式
在多型的情形下也會先進入 derived 的 intersection 函式
arr[0]->intersection(*arr[1]);
會印出 In point 代表是在 CPoint 內的 intersection 函式
也代表了在動態時可以推出 *this 是 CPoint 才對 @@
在這個情況下 我使用 rhs.intersection(*this) (註解的地方!!)
理論上應該 rhs會經由多型 得知自己是 CSphere
再經由重載 選出要執行 intersection(const CPoint&) 這個函式
可是在編譯時卻會出現
error C2663: 'CGeometry::intersection' :
3 overloads have no legal conversion for 'this' pointer
請問要怎要修改才會是正確的寫法??
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.210.75
※ 編輯: ytli1204 來自: 140.113.210.75 (04/13 16:53)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.210.75
討論串 (同標題文章)
完整討論串 (本文為第 1 之 2 篇):