提问人:Sachin Palande 提问时间:11/25/2021 更新时间:11/25/2021 访问量:125
在面试中,我要求写构造函数、复制构造函数和赋值运算符
In Interview, I asked to write constructor, Copy constructor and assignment operator
问:
在面试中,我要求写构造函数、复制构造函数和赋值运算符。我写了以下代码。
然后他问我,按照我无法回答的代码有什么问题,你能帮我知道哪里出了问题吗?
另外,从问题中,面试官试图找到什么?
//constructor, copy constructor, assignment operator and destructor
class Employee
{
int id;
char *name;
public:
//constructor
Employee()
{
id=0;
*name = new char[];
}
//Copy constructor
Employee (const Employee& oldObj)
{
id = oldObj.id;
*name = *(oldObj.name);
}
//destructor
~Employee()
{
delete[] name;
}
//Assignment operator overloading
void operator = (const Employee& obj)
{
id = obj.id;
delete[] name;
*name = *(obj.name);
}
};
int main()
{
Employee a1;
Employee a2 = a1; //copy constructor
Employee a3;
a3 = a1;//assignment operator
}
答:
0赞
eerorika
11/25/2021
#1
以下代码有什么问题
- 使用裸露的自有指针,而不是智能指针或容器。
*name = pointer
格式不正确。new char[]
格式不正确。
评论
a = b = c;
new char[]
也是无效的 - 要么你只需要一个字符( 或 ),但随后你需要 - 或者你需要指定一个数组大小(因为你似乎总是只使用一个字符) - 第一次尝试,稍后你可能想要更长的数组......new char;
new char()
delete name
new char[1]
delete[]
std::initializer_list
Employee() : id(0), name(new char[1]) {}
const
char*
std::string