我有以下代码
#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;
}
p1
调用构造函数后,为什么会出现分段错误?*p1 = new myClass;
行,&#34; PP7myClass&#34;和&#34; A5_P7myClass&#34;印刷,什么是&#34; PP7&#34;和&#34; A5_P7&#34;?void func(myClass a, myClass b){}
然后执行func(p1, p2);
,编译器会抱怨无法将myClass **
转换为myClass
两个参数,这意味着{{ 1}}和p1
都属于p2
类型,但为什么对于myClass **
以上的两行,什么都没有打印?答案 0 :(得分:2)
为p1调用构造函数后,为什么会出现分段错误?
myClass ** p1;
说“用于指针指针的gimme空间”;不是“在这个单位指针所指向的点处给予空间”。
2。 醇>
他们是打字员。
3
你没有初始化pc
或p
是什么:我想知道为什么你的编译器不会阻止你这样做,但似乎pc
没有p
类型{1}}也不是*p
。
编辑:
编辑后的:指针和数组的类型不一样。
答案 1 :(得分:2)
p1
本身并没有真正指出某些事情。所以*p1
取消引用未初始化的内存
它们是由编译器构造的名称标记的类型名称。请参阅http://en.wikipedia.org/wiki/Name_mangling
我没有在代码中看到pc
变量或类型已定义/声明。 编辑因为f()
的原型要求传递类型myClass
的参数。 p2
也属于myClass**
;它是指向myClass
的指针数组的名称,并退化为myClass**
类型,请参阅standard conversions: Array-to-pointer conversion