[問題] C++ Primer 4/e ch14問題
使用平台: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
08/11 15:26, 1F
→
08/11 15:28, , 2F
08/11 15:28, 2F
→
08/11 15:31, , 3F
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
08/11 15:52, 6F
→
08/11 16:00, , 7F
08/11 16:00, 7F
※ 編輯: Zephyr750 來自: 59.120.98.237 (08/11 16:00)
→
08/11 16:01, , 8F
08/11 16:01, 8F
→
08/11 16:01, , 9F
08/11 16:01, 9F
→
08/11 16:02, , 10F
08/11 16:02, 10F
※ 編輯: Zephyr750 來自: 60.244.112.65 (08/11 16:23)
→
08/11 16:24, , 11F
08/11 16:24, 11F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章