代码不能接受名称的输入? [英] The code is not able to take the input for name?
本文介绍了代码不能接受名称的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法对类进行任何更改,因此我无法添加任何为我设置名称的新函数.
No changes to the class can be done so I cant add any new functions which sets the name for me.
class ele
{
char* name;
public:
ele() :name(nullptr){}
~ele()
{
if (name)
delete[]name;
}
char*& GetName();
};
#endif
我尝试访问该名称,但在 cin Debug 断言失败后出现错误.无效的空指针.
I try to access the name but it gives me error after cin Debug assertion failed. Invalid null pointer.
> ` char*& ele::GetName()
{
cout << "Please Enter the name"<< endl;
cin >> this->name;
return this->name;
}`
推荐答案
如果你不能改变你的类(并使用 std::string
)你至少需要在 cin> 之前分配内存;>this->name
,现在您使用的是 UB 的空指针.因此,您的修复将如下所示:
If you cannot change your class (and use std::string
) you need to at least allocate memory before cin>>this->name
, now you are using a null poitner which is UB. So your fix would look as follows:
if (this->name == nullptr)
this->name = new char[64]; // << !!
cin >> this->name;
这篇关于代码不能接受名称的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文