2013-04-21 114 views
3

在C++中,Type **Type const **轉換被禁止。此外,不允許將derived **轉換爲Base **C++禁止指針轉換指針

這些轉換爲什麼會出現wtong?還有其他的例子指針轉換指針不能發生?

是否有解決辦法:如何將一個指針指向Type類型的非const對象轉換爲指針指向Type類型的const對象,因爲Type ** - >Type const **不會使它?

+1

爲什麼*應該*允許?你通常不能將'U *'轉換爲'W *',因爲這沒有意義... – 2013-04-21 12:06:56

+0

可能的重複[爲什麼不能將\ char \ * \ * \'傳遞給一個函數在C中使用\'const char \ * \ * \?](http://stackoverflow.com/questions/3496000/why-is-it-not-ok-to-pass-char-to-a-function -that-takes-a-const-char-in) – 2013-04-21 13:38:21

+0

我想在兩個轉換禁令之間繪製並行,這不是您提到的線程的要點。 WIM,我在問什麼其他轉換禁令是一樣的。 – octoback 2013-04-21 15:51:14

回答

5

Type *const Type*被允許:

Type t; 
Type *p = &t; 
const Type*q = p; 

*p可以通過p通過q被修改但尚未。

如果Type **const Type**轉換被允許,我們可能有

const Type t_const; 

Type* p; 
Type** ptrtop = &p; 

const Type** constp = ptrtop ; // this is not allowed 
*constp = t_const; // then p points to t_const, right ? 

p->mutate(); // with mutate a mutator, 
// that can be called on pointer to non-const p 

最後一行可能會改變const t_const

對於derived **Base **轉換,當Derived1Derived2類型從相同Base派生髮生問題。然後,

Derived1 d1; 
Derived1* ptrtod1 = &d1; 
Derived1** ptrtoptrtod1 = &ptrtod1 ; 

Derived2 d2; 
Derived2* ptrtod2 = &d2; 

Base** ptrtoptrtobase = ptrtoptrtod1 ; 
*ptrtoptrtobase = ptrtod2 ; 

Derived1 *指向一個Derived2

Type **指向指向const的指針的正確方法是使其成爲Type const* const*

+1

不幸的是,變量名是不可讀的。簡單地用'p'代替'ptrto'實際上應該會有所幫助。 – 2013-04-21 12:17:29

+0

謝謝,第一個例子中的簡化表示法 – octoback 2013-04-21 15:48:43

+0

不會有'* ptrtoptrtobase = ptrtod2;'導致切片? (我不知道是否用指向父類的指針產生切片) – jdehesa 2017-08-18 09:58:14