在C++中,Type **
到Type const **
轉換被禁止。此外,不允許將derived **
轉換爲Base **
。C++禁止指針轉換指針
這些轉換爲什麼會出現wtong?還有其他的例子指針轉換指針不能發生?
是否有解決辦法:如何將一個指針指向Type
類型的非const對象轉換爲指針指向Type
類型的const對象,因爲Type **
- >Type const **
不會使它?
在C++中,Type **
到Type const **
轉換被禁止。此外,不允許將derived **
轉換爲Base **
。C++禁止指針轉換指針
這些轉換爲什麼會出現wtong?還有其他的例子指針轉換指針不能發生?
是否有解決辦法:如何將一個指針指向Type
類型的非const對象轉換爲指針指向Type
類型的const對象,因爲Type **
- >Type const **
不會使它?
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 **
轉換,當Derived1
和Derived2
類型從相同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*
。
爲什麼*應該*允許?你通常不能將'U *'轉換爲'W *',因爲這沒有意義... – 2013-04-21 12:06:56
可能的重複[爲什麼不能將\ 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
我想在兩個轉換禁令之間繪製並行,這不是您提到的線程的要點。 WIM,我在問什麼其他轉換禁令是一樣的。 – octoback 2013-04-21 15:51:14