为什么我的重载构造函数会导致崩溃?

时间:2019-05-21 18:04:38

标签: visual-c++

基本上,当重载运算符(operator--)构造函数时 我的程序崩溃了,将类数组从动态数组更改为静态数组, 解决了问题,那是为什么?

如果将类数组从动态更改为静态,则重载有效 很好,但这不是我正在寻找的解决方案。

具有静态数组的工作版本:

#include <iostream>
#include<string>
using namespace std;
const int TABLE = 10;

class Player()
{
private:
        int health;
        string A[TABLE][TABLE];
public:
      Player()
      {
         health = 17;
         for (int i = 0; i < TABLE; i++)
         {
             for (int j = 0; j < TABLE; j++)
                 A[i][j] = "-";
         }
      }
      Player(int new_health)
      {
             health = new_health;
      }
      Player operator--()
      {
             health--;
             return Player(health);
      }
      ~Player(){}
};

int main()
{
   Player p1; // Creates object p1 and calls Player(), initializing 
health variable, and string A array.
   --p1; // Decrements p1 health value
   return 0;
} 

动态数组版本:

#include <iostream>
#include<string>
using namespace std;
const int TABLE = 10;

class Player()
{
private:
        int health;
        string **A;
public:
      Player()
      {
         health = 17;
         A = new string*[TABLE];
         for (int i = 0; i < TABLE; i++)
         {
            A[i] = new string[TABLE];
         }
         for (int i = 0; i < TABLE; i++)
         {
             for (int j = 0; j < TABLE; j++)
                 A[i][j] = "-";
         }
      }
      Player(int new_health)
      {
             health = new_health;
      }
      Player operator--()
      {
            health--;
            return Player(health);
      }
      ~Player()
      {
            for (int i = 0; i < TABLE; i++)
                 delete[] A[i];
            delete[] A;
      }
};

int main()
{
    Player p1; // Creates object p1, calls Player(), set health value, 
initializes dynamic array
    --p1; // Produces a crash with exit status -1
    return 0;
}

没有错误消息,运行状况= new_health时不会发生崩溃 部分,一旦Player(int new_health)构造函数完成,它就会崩溃 它的工作。动态数组如何影响重载构造函数并导致崩溃?

1 个答案:

答案 0 :(得分:0)

发生错误是因为您在-重载中创建的新播放器实例被破坏;但是,构造函数重载从未初始化动态数组。因此,在调用析构函数时,您将尝试删除未分配的内存。