c++ - 混淆 myClass ** p1 和 myClass *p2[5]

标签 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; 被注释掉,打印“PP7myClass”和“A5_P7myClass”,那么“PP7”和“A5_P7”是什么?
  3. 如果我定义一个函数 void func(myClass a, myClass b){} 然后执行 func(p1, p2);,编译器会报错不将两个参数的 myClass ** 转换为 myClass,这意味着 p1p2 都是类型 myClass **,但是为什么上面两行return 0;没有打印出来呢?

最佳答案

  1. p1 本身实际上并不指向某物。所以 *p1 解引用未初始化的内存

  2. 它们是由编译器构造的类型的名称修饰名称。参见 http://en.wikipedia.org/wiki/Name_mangling

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

关于c++ - 混淆 myClass ** p1 和 myClass *p2[5],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29065142/

相关文章:

C++ : Unable to print the text formatted as expected

c# - 我可以让 Memcached 在 Windows (x64) 64 位环境中运行吗?

c++ - 派生类和类型检查

c++ - 覆盖不明确的继承

c++ - 引用表溢出(最大值=1024)

c++ - 如何将 Char** 插入 uin8_t vector ?

c++ - 如何检查 C++ 编译时是否存在运算符的特定重载?

java - java this的C++版本。在类里面

c++ - 背后的原因:尽管按名称返回,本地变量 'derived'仍将被复制

c++ - Arduino Nano - 为什么我的针脚是这样的?