为什么这个程序会崩溃?我分配内存错了吗
Why is this program crashing ? Did I wrongly allocate memory?
问题
设计一个包含姓名和员工编号的类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;
}
您没有为title
或name
分配任何内存,因此无法从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*
。它自己分配内存,你不必释放任何东西,复制也很好。
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 如果 const 不分配内存,为什么我可以获取 const 的地址?
- 在函数中分配内存时出现问题
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- constexpr new 如何分配内存?
- 在构造函数中分配内存失败是如何冒泡的
- LLVM 传递以在特定地址分配内存
- CudaMalloc 在分配内存时失败
- 为什么它在不分配内存的情况下工作正常
- 为什么在正确解除分配内存时出现内存泄漏?
- 如何通过 malloc 为队列数组分配内存?
- vector是否为std::移动的对象连续分配内存
- 删除类成员的动态分配内存的最佳方法是什么
- 唯一指针是否在堆或堆栈上分配内存?
- 如果不分配内存,我如何能够为变量创建和分配值?
- std::initializer_list 堆是否分配内存?
- 如何按顺序或在指定的地址分配内存?
- 是否可以使用 malloc 为类对象分配内存?
- 迭代器是否分配内存(如指针)?