【问题标题】:Making an array of pointer to classes制作一个指向类的指针数组
【发布时间】:2016-04-04 11:48:49
【问题描述】:

我正在尝试创建一个包含指向类的指针的数组。 数组的大小将由键盘给出,所以我尝试使用以下方式创建数组:

 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 ;
        }
  }
}

然后我尝试打印数组

    cout << endl << "Printing Society:" << endl ;
    for ( j = 0 ; j <= N -1 ; j++)
    {
       temp = (*( cs1.get_A() + j ))->get_crt_name() ;
    }

问题是,当我在 linux 上运行时遇到分段错误,而在 Dev C++ 上运行良好(大部分时间)! 您指出了哪些错误?

【问题讨论】:

  • 你反对std::vector&lt;creature*&gt;吗?它会让你的生活更轻松。
  • @CoryKramer:呃,为什么要存储原始指针??
  • @LightnessRacesinOrbit 好的,最好是std::vector&lt;std::unique_ptr&lt;creature&gt;&gt;。婴儿步骤:)
  • @CoryKramer:我们不要把超锋利的斧子给婴儿,嗯? :)
  • @LightnessRacesinOrbit 肯定原始指针是工具箱中最锋利的斧头吗?只用于最坚硬的树?

标签: c++ arrays class pointers segmentation-fault


【解决方案1】:

您在这里没有提到bad_creaturegood_creature 的类。 我假设他们继承了作为基类的类,因此您应该将get_crt_name 定义为一个虚函数。

也许你的get_unique_name 函数也出了问题。 我在 VC2015 中执行了您的代码,没有发现任何错误(我将 good creaturebad creature 类替换为 creature,并将 get_unique_name 替换为 const 字符串)。

请:

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

对于未来,类名应始终以大写字母开头,因为这是一种非常常见的样式约定。

【讨论】:

  • @CoryKramer 我会相应地编辑我的答案,尽管我真的很讨厌遇到以小写字母开头的类定义..(当然,除非它们来自 std)
  • 我遇到了一个奇怪的问题,伙计们,
  • @Social Programmer 好,不写就帮不上忙了
【解决方案2】:

我认为你可以简单地做到,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2019-01-18
    • 2021-02-07
    • 2011-05-10
    • 2012-05-12
    相关资源
    最近更新 更多