2013-04-21 109 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