崩溃,可能是由于构造函数或析构函数中的某些问题

时间:2014-10-30 17:23:07

标签: c++ constructor

我设法隔离了一个导致程序崩溃的错误,但我还无法弄清楚这个问题。我想问题是调用对象lookProfile和lookContacts的默认构造函数,因为一旦我删除了这些行,程序就会顺利运行。

这是主要的。

#include <iostream>
#include <fstream>
#include "profile.h"
#include "contact.h"
#include <sstream>

using namespace std;

void Query(profile* &lsp,int,ofstream& outt);

int main()
{
    ifstream inn;
    ofstream outt;

    char resp;

    profile *listp;

    int length=0;

    listp = new profile[50];

    inn.open("profiles.txt");     // retrieve profiles
    retrieveProfiles(inn,listp,length);
    inn.close();

    cout << "Do you want to add your profile or to look for someone? (A/L)";
    cin >> resp;

    if(resp=='A')
    {
        outt.open("profiles.txt",ios::app);
        addProfile(outt);
        outt.close();
    }else if(resp=='L')
    {
        outt.open("contacts.txt",ios::app);
        Query(listp,length,outt);
        outt.close();
    }
    else
        cout << "Wrong Input";

    return 0;
}

void Query(profile* &lsp,int length,ofstream& outt)
{
    const int THRESHOLD = 3;

    string str;
    int num,numvec[3];
    int *overthreshold;
    int countOver=0;
    char dis;
    profile lookProfile;
    contact lookContact;
}

这些是类概要文件的私有成员以及构造函数和析构函数的实现:

 private:
     std::string name;
     std::string surname;
     int age;
     std::string icolor;
     int height;
     std::string homeTown;
     std::string livingTown;
     std::string *hobby;
     int lenghob;
     int ID;

profile::profile() //ctor
{
    name="";
    surname="";
    age=0;
    height=0;
    icolor="";
    homeTown="";
    livingTown="";
    lenghob=0;
    ID=0;
}

profile::~profile() //dtor
{
    delete [] hobby;
}

这些是类接触的私有成员以及构造函数和析构函数的实现:

 private:
     int date[3];
     std::string time;
     std::string place;
     std::string address;
     std::string *keywords;
     int lengthkw;

contact::contact()      //ctor
{
    for(int i=0;i<3;i++)
        date[i]=1;

    time="12:00-13:00";
    place="";
    address="";
    lengthkw=0;
}

contact::~contact()
{
     delete [] keywords; //dtor
}

提前致谢。

1 个答案:

答案 0 :(得分:3)

您已将hobbykeywords定义为std::string指针,但您未通过调用new初始化它们。但是,在析构函数中,您正在调用delete来对付它们。由于它们是垃圾,你会得到未定义的行为,所以可能是崩溃。

相关问题