Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 生成指向类的指针数组_C++_Arrays_Class_Pointers_Segmentation Fault - Fatal编程技术网

C++ 生成指向类的指针数组

C++ 生成指向类的指针数组,c++,arrays,class,pointers,segmentation-fault,C++,Arrays,Class,Pointers,Segmentation Fault,我试图创建一个数组,其中包含指向类的指针。 数组的大小将由键盘给出,因此我尝试用以下方法创建数组: class creature { protected: string crt_name ; int L ; public: creature( int Life = -1 , string Name = "") : L(Life) , crt_name(Name){} string get_crt_n

我试图创建一个数组,其中包含指向类的指针。 数组的大小将由键盘给出,因此我尝试用以下方法创建数组:

 class creature
 {
    protected:
      string crt_name ;
      int L ;   
    public:
       creature( int Life = -1 , string Name = "")
        : L(Life) , crt_name(Name){} 

       string get_crt_name ( void )
       { 
          return crt_name ;
       }
 }; 

 class creature_society
 {
    private:
       creature* *A ;
       int noc ;
    public:
       creature_society( int , int ) ;
       ~creature_society() ;
       creature** get_A ( void ){return A ;}
 };
生物社团的建造师将用随机制造的生物填充阵列

creature_society::creature_society( int life , int number_of_creatures )
{
   noc =  number_of_creatures ;
   A = new creature*[noc] ;

   creature* temporary ;

   for( int  i = 0 ; i<= number_of_creatures -1 ; i++)
   {
     if ( rand()%100 <= 50) 
        {
            temporary = new good_creature( life , get_unique_name( 3 ) );
            A[i] = temporary ;
        }
        else
        {
            temporary = new bad_creature( life , get_unique_name( 3 ) );
            A[i] = temporary ;
        }
  }
}
生物协会::生物协会(整数生命,整数个生物)
{
noc=生物的数量;
A=新生物*[noc];
生物*临时;

对于(int i=0;i我想你可以

for (int j=0 ; j < N; ++j)
{
   temp = cs1.get_A()[j]->get_crt_name();
}
for(int j=0;jget_crt_name();
}

这里您没有提到
坏生物
好生物
的类别。 我假设它们继承生物作为基类,因此您应该将
get\u crt\u name
定义为虚拟函数

您的
get\u unique\u name
函数也可能出了问题。 我在VC2015中执行了您的代码,没有发现任何错误(我用
生物
替换了
好生物
坏生物
类,并用常量字符串替换了
获取唯一名称

请:

1.检查核心转储程序在哪里崩溃。 2.在分段故障之前,它发出了什么输出


将来,类名应该总是以大写字母开头,因为这是一种非常常见的样式约定。

你反对
std::vector
?这会让你的生活更轻松。@CoryKramer:Ew,为什么要存储原始指针???@LightnessRacesinOrbit好吧,更好的做法是
std::vector
。小步骤:)@CoryKramer:让我们不要把超级锋利的斧子给婴儿吧?:)@LightnessRacesinOrbit当然一个原始指针是工具棚里最锋利的斧子?只用于最坚硬的树?@CoryKramer我会相应地编辑我的答案,尽管我真的不喜欢遇到以小写字母开头的类定义。。(当然,除非他们来自std)我遇到了一个奇怪的问题,伙计们,@Social Programmer嗯,如果你不把他们写下来就帮不上忙了
for (int j=0 ; j < N; ++j)
{
   temp = cs1.get_A()[j]->get_crt_name();
}