[問題] C++ Primer 4/e ch14問題

看板C_and_CPP (C/C++)作者 (紅蓮西風750)時間12年前 (2011/08/11 14:53), 編輯推噓0(0011)
留言11則, 3人參與, 最新討論串1/1
使用平台:VC++6 //範例中沒有,隨意定義內容的Screen class class Screen { public: int a; }; class ScrPtr { friend class ScreenPtr; Screen *sp; size_t use; ScrPtr(Screen *p):sp(p), use(1){} ~ScrPtr(){delete sp;} }; class ScreenPtr { public: //沒有default建構式:ScreenPtrs必須綁定於某個物件上 ScreenPtr(Screen *p):ptr(new ScrPtr(p)){} //拷貝成員並累加參用計數 ScreenPtr(const ScreenPtr &orig):ptr(orig.ptr){ ++ptr->use; } ScreenPtr& operator=(const ScreenPtr&); //如果參用計數為0,刪除StrPtr物件 ~ScreenPtr(){ if(--ptr->use == 0) delete ptr; } const Screen& operator*() const{ return *ptr->sp;} //錯誤訊息出現時指著這一行 const Screen* operator->() const{ return ptr->sp;} Screen& operator*(){ return *ptr->sp;} Screen* operator->(){ return ptr->sp;} private: ScrPtr *ptr;//指向被計數的ScrPtr }; error訊息: --------------------Configuration: ch14 - Win32 Debug-------------------- Compiling... main.cpp d:\c++primer4\ch14\screenptr.h(11) : error C2440: 'return' : cannot convert from 'class Screen' to 'const class ScreenPtr &' Reason: cannot convert from 'class Screen' to 'const class ScreenPtr' No constructor could take the source type, or constructor overload resolution was ambiguous d:\c++primer4\ch14\screenptr.h(12) : error C2440: 'return' : cannot convert from 'class Screen *' to 'const class ScreenPtr *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast d:\c++primer4\ch14\screenptr.h(13) : error C2440: 'return' : cannot convert from 'class Screen' to 'class ScreenPtr &' A reference that is not to 'const' cannot be bound to a non-lvalue d:\c++primer4\ch14\screenptr.h(14) : error C2440: 'return' : cannot convert from 'class Screen *' to 'class ScreenPtr *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast Error executing cl.exe. ch14.exe - 4 error(s), 0 warning(s) 請問是發生了什麼問題?? 是不是const 的refrence和const的derefrence不可以放non-const呢? 不過已經重載了,怎麼還會?? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.248.125.78 ※ 編輯: Zephyr750 來自: 60.248.125.78 (08/11 14:55) ※ 編輯: Zephyr750 來自: 60.248.125.78 (08/11 14:58)

08/11 15:26, , 1F
你應該要return ptr->sp;吧 ScreenPtr的ctor是吃Screen*
08/11 15:26, 1F

08/11 15:28, , 2F
不過這寫法怎覺得邏輯怪怪的~"~
08/11 15:28, 2F

08/11 15:31, , 3F
撤回一樓 那樣會return reference to temporary object...
08/11 15:31, 3F

08/11 15:38, , 4F
*和->的優先權確認一下
08/11 15:38, 4F

08/11 15:43, , 5F
->優先於*
08/11 15:43, 5F

08/11 15:52, , 6F
ptr->sp是指向ScrPtr.sp, *ptr->sp是Screen
08/11 15:52, 6F

08/11 16:00, , 7F
找到問題了!純粹是看錯字!key錯了!sorry
08/11 16:00, 7F
※ 編輯: Zephyr750 來自: 59.120.98.237 (08/11 16:00)

08/11 16:01, , 8F
ScreenPtr改成Screen就好了!返回型別打錯字!XDDD
08/11 16:01, 8F

08/11 16:01, , 9F
所以說應該要return Screen&或Screen*嘛
08/11 16:01, 9F

08/11 16:02, , 10F
一直return自己難怪邏輯很怪XD
08/11 16:02, 10F
※ 編輯: Zephyr750 來自: 60.244.112.65 (08/11 16:23)

08/11 16:24, , 11F
純排版修改
08/11 16:24, 11F
文章代碼(AID): #1EGtnriu (C_and_CPP)
文章代碼(AID): #1EGtnriu (C_and_CPP)