为什么这个程序会崩溃?我分配内存错了吗

Why is this program crashing ? Did I wrongly allocate memory?

本文关键字:分配 内存 错了 崩溃 程序 为什么      更新时间:2023-10-16

问题

设计一个包含姓名和员工编号的类Employee。衍生经理、科学家和劳工课程。经理类有额外的属性title和duce。科学家类具有额外的出版物数量属性。劳工阶层没有多余的东西。类具有设置和显示信息的必要功能。

我的解决方案

#include<iostream>
#include<cstring>
using namespace std;
class employee
{
protected:
    char *name;
    int number;
public:
    employee()
    {
        cout<<"enter employee name  n";
        cin>>name;
        cout<<"enter employee number n";
        cin>>number;        
    }
    void display()
    {
        cout<<"name t"<<name<<endl;
        cout<<"number t"<<number<<endl;
       // inside class function is a inline function
    }        
};
class manager: private employee 
{
    float due;
    char *title;
    public: 
    manager( )
    {
        cout<<"duet "<<endl; 
        cin>>due;
        cout<<"titlet"<<endl;
        cin>>title;
        fflush(stdin);
    }
    void display()
    {
        employee::display();     //inside class function is a inline function
        cout<<"duet"<<due<<endl;
        cout<<"titlet"<<title<<endl;
        //inside class function is a inline function
    }
};
class labour :private employee
{
public:
    void display()
    {    
        employee::display();      //inside class function is a inline function
    }
}; 
class  Scientist :private employee
{
    int number;
public:
    Scientist()
    {    
        cout<<"publication number "<<endl;
        cin>>Scientist::number;
    }
    void display()                  
    {
        employee::display();  
        cout<<" pub number "<<Scientist::number<<endl;
        fflush(stdin);
    }  //inside class function is a inline function
};
int  main()
{
    manager m;
    m.display();        
    Scientist s;
    s. display();
    labour l;
    l.display();
    return 0;
}

您没有为titlename分配任何内存,因此无法从std::cin读取它们。与其使用char*,不如使用std::string,它将为您完成所有分配:

std::string title;
std::string name;

empolyee的构造函数中,读取未初始化的char*。因此,它不会指向一个有效的内存块,您可以在其中存储输入的名称

name = static_cast<char*>(malloc( 32 * sizeof(char) ));

分配内存以使名称指向有效内存,但您总是浪费内存或没有足够的内存用于输入。你还必须释放析构函数中的内存。

正如Peter Schneider在这个答案的评论中所写的,另一种选择是使用固定大小的数组作为成员,例如

char name[MAX_NAME_LENGTH];

具有例如预处理器定义的

#define MAX_NAME_LENGTH 64

在文件的顶部。复制构造函数通过这种方式完成他的工作。对于作为成员的指针,您总是必须自己编写它们,否则,原始类实例和复制实例将有一个指向同一内存的成员指针。因此,如果复制的实例更改了名称,则原始实例的名称也将更改。

最简单的解决方案是使用std::string而不是char*。它自己分配内存,你不必释放任何东西,复制也很好。