代码无法输入名称?
问题描述:
没有对类进行任何更改,因此我不能添加任何为我设置名称的新函数。代码无法输入名称?
class ele
{
char* name;
public:
ele() :name(nullptr){}
~ele()
{
if (name)
delete[]name;
}
char*& GetName();
};
#endif
我尝试访问该名称,但它给我错误后cin调试断言失败。无效的空指针。
> ` char*& ele::GetName()
{
cout << "Please Enter the name"<< endl;
cin >> this->name;
return this->name;
}`
答
如果你不能改变你的类(和使用std::string
),你需要cin>>this->name
之前至少分配内存,现在使用的是空poitner这是UB。所以你的修正看起来如下:
if (this->name == nullptr)
this->name = new char[64]; // << !!
cin >> this->name;
'this-> name'是'nullptr'因为这就是你在构造函数中初始化它的方式。你不能从'std :: cin'读入'nullptr'。您需要在某个时间点分配存储空间并将'name'设置为指向它。你可以通过使用'std :: string'来节省很多麻烦。 –
我很想知道'char *&'类型是什么? – 2017-02-03 19:03:13
告诉写这个可怕类的人,析构函数中的'nullptr'检查是多余的。 –