0

代码最后一步的目的是创建一个类的临时实例,在该类的私有数据成员上使用一个集合,在该实例仍在作用域内时打印出该实例,然后使用一个析构函数来处理指针和类实例。我收到了分段错误错误,即使进行了很多更改,我也已经收到了一段时间,所以这让我非常沮丧。

 #include <cstdlib>
 #include <iostream>
 #include <cstring>

using namespace std;


//Class Definition

class Box{

      //Private data members
      private:
      int height;
      int width;
      int depth;
      char *name;
      void pri_setname(char *n);

      public:
      //Public constructors and deconstructor
      Box(int,int,int,char *);
      Box(const Box &obj);
      ~Box();
      //Public function prototypes
      void width_set(int w);
      void height_set(int h);
      void depth_set(int d);
      void name_set(char *n);
      void name_print();
      int volume_print();
      void objCreateKeep(Box **, char *n);
      void objCreateTmp(char *n);
};

//Default constructor
Box::Box(int h1 = 1,int w1 =1, int d1 =1,char *n1 = "Blue Box")
{
  strcpy(name,n1);
  height = h1;
  width = w1;
  depth  = d1;

}
//Copy constructor
Box::Box(const Box &obj)
{
  name = new char[25];
  strcpy(name,obj.name);
  height = obj.height;
  width = obj.width;
  depth = obj.depth;
}
//Destructor
Box::~Box()
{
  delete [] name;
  cout<<"Destructor invoked, name pointer is deallocated";
}

void Box::pri_setname(char *n)
{
   strcpy(name,n);  
}

//Set the width of Box()
void Box::width_set(int w)
{
     width = w;
}

//Set the height of Box()
void Box::height_set(int h)
{
     height = h;
}

//Set the depth of Box()
void Box::depth_set(int d)
{
     depth = d;
}

//Set the name of Box()
void Box::name_set(char *n)
{
    name = new char[30];
    strcpy(name,n);
    pri_setname(name);
}

//Prints the name of the box
void Box::name_print()
{
  cout<<"Box Name: "<<name;
}

//Calculate and Print volume of Box()
int Box::volume_print()
{
   int volume = 0;
   volume = height * width * depth;
   return volume ;
}


void Box::objCreateTmp(char *n)
{
   Box tmp;
   tmp.name_set(n);
   tmp.name_print();
   tmp.~Box();
}

void Box::objCreateKeep(Box **pp, char *n)
{
  Box *p = new Box;
  pp = &p;
  p->objCreateTmp(n);
  delete p;
}


int main(int argc, int argv[])
{

    //Check for correct # of cmd line args
    /*
    if(argc != 3)
    {
      cout<<"Wrong number of arguments";
    }
    */
/*
    Box a;
    a.height_set(argv[1]);
    a.width_set(argv[2]);
    a.depth_set(argv[3]);

    Box b = a;
    Box c = a;

    //Set the names of box B and C
    b.name_set("Red Box");
    c.name_set("Orange Box");

    a.name_print();
    b.name_print();
    c.name_print();


*/
    Box *keep;
    Box **pp;

    keep->objCreateKeep(pp,"Blue Box");
    keep->objCreateKeep(pp,"Red Box");
    keep->objCreateKeep(pp,"Orange Box");


    system("PAUSE");
    return(0);
}
4

2 回答 2

0

除了这里的其他答案:

tmp.~Box();- 不。

析构函数在超出范围时被调用。

delete [] name;

在你的析构函数中被调用,现在它将被调用两次。坏的。

于 2013-02-15T04:01:53.407 回答
0

在行

pp = &p;

您将addressof分配ppp

当你deletep 时,你记得它住在哪里并不重要......

p->objCreateTmp(n);
delete p;
于 2013-02-15T04:02:05.447 回答