作者Zephyr750 (紅蓮西風750)
看板C_and_CPP
標題[問題] C++ Primer 4/e ch14問題
時間Thu Aug 11 14:53:39 2011
使用平台: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)
→ PkmX:你應該要return ptr->sp;吧 ScreenPtr的ctor是吃Screen* 08/11 15:26
→ PkmX:不過這寫法怎覺得邏輯怪怪的~"~ 08/11 15:28
→ PkmX:撤回一樓 那樣會return reference to temporary object... 08/11 15:31
→ DarkNT:*和->的優先權確認一下 08/11 15:38
→ Zephyr750:->優先於* 08/11 15:43
→ Zephyr750:ptr->sp是指向ScrPtr.sp, *ptr->sp是Screen 08/11 15:52
→ Zephyr750:找到問題了!純粹是看錯字!key錯了!sorry 08/11 16:00
※ 編輯: Zephyr750 來自: 59.120.98.237 (08/11 16:00)
→ Zephyr750:ScreenPtr改成Screen就好了!返回型別打錯字!XDDD 08/11 16:01
→ PkmX:所以說應該要return Screen&或Screen*嘛 08/11 16:01
→ PkmX:一直return自己難怪邏輯很怪XD 08/11 16:02
※ 編輯: Zephyr750 來自: 60.244.112.65 (08/11 16:23)
→ Zephyr750:純排版修改 08/11 16:24