混淆myClass ** p1和myClass * p2 [5]

时间:2015-03-15 19:24:56

标签: c++

我有以下代码

#include <iostream>
#include <typeinfo>
using namespace std;
class myClass{
     public:
      myClass(){
        cout<<"constructor called..."<<endl; }
};

int main(){
   myClass ** p1;
   myClass *p2[5];

   *(p2+4) = new myClass;
   *p1 = new myClass;  // "constructor called..." printed, but segmentation fault

   cout<<typeid(p1).name()<<endl; 
   // "PP7myClass" printed, after commenting out *p1 = new myClass;
   // what is PP7?
   cout<<typeid(2).name()<<endl; 
   // "A5_P7myClass" printed, after commenting out *p1 = new myClass; 
   //  what is A5_P7?

   if(typeid(p1)==typeid(p2)) cout<<"==="<<endl; 
   if(typeid(p1)==typeid(*p2)) cout<<"&&&"<<endl;
   // I expected at least one of the above cout 
   // two lines should be printed, but nothing printed actually, why?


   return 0;
   }
  1. p1调用构造函数后,为什么会出现分段错误?
  2. 如果注释掉*p1 = new myClass;行,&#34; PP7myClass&#34;和&#34; A5_P7myClass&#34;印刷,什么是&#34; PP7&#34;和&#34; A5_P7&#34;?
  3. 如果我定义一个函数void func(myClass a, myClass b){}然后执行func(p1, p2);,编译器会抱怨无法将myClass **转换为myClass两个参数,这意味着{{ 1}}和p1都属于p2类型,但为什么对于myClass **以上的两行,什么都没有打印?

2 个答案:

答案 0 :(得分:2)

  

为p1调用构造函数后,为什么会出现分段错误?

myClass ** p1;

说“用于指针指针的gimme空间”;不是“在这个单位指针所指向的点处给予空间”。

  
      2。   

他们是打字员。

  

3

你没有初始化pcp是什么:我想知道为什么你的编译器不会阻止你这样做,但似乎pc没有p类型{1}}也不是*p

编辑:

编辑后的

:指针和数组的类型不一样。

答案 1 :(得分:2)

  1. p1本身并没有真正指出某些事情。所以*p1取消引用未初始化的内存

  2. 它们是由编译器构造的名称标记的类型名称。请参阅http://en.wikipedia.org/wiki/Name_mangling

  3. 我没有在代码中看到pc变量或类型已定义/声明。 编辑因为f()的原型要求传递类型myClass的参数。 p2也属于myClass**;它是指向myClass的指针数组的名称,并退化为myClass**类型,请参阅standard conversions: Array-to-pointer conversion