在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