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

Crash, possibly due to some issue in the constructor or destructor

本文关键字:析构函数 问题 构造函数 崩溃      更新时间:2023-10-16

我设法隔离了一个导致程序崩溃的错误,但我还不能解决这个问题。我想问题出在对对象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
}

提前谢谢。

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