现有一学生类定义: class Student{ …….. private: int _id; string _name; char *_addr; }; 实现学生类的赋值运算符=重载,主函数调用赋值运算符并输出对象信息。
时间: 2023-05-23 14:03:49 浏览: 130
好的,我可以回答这个编程问题。下面是实现学生类赋值运算符的代码:
```
#include <iostream>
#include <cstring>
using namespace std;
class Student{
public:
Student(int id, string name, char* addr){
_id = id;
_name = name;
_addr = new char[strlen(addr)+1];
strcpy(_addr, addr);
}
Student(const Student& stu){
_id = stu._id;
_name = stu._name;
_addr = new char[strlen(stu._addr)+1];
strcpy(_addr, stu._addr);
}
~Student(){
delete [] _addr;
}
Student& operator=(const Student& stu){
if(this == &stu)
return *this;
_id = stu._id;
_name = stu._name;
delete [] _addr;
_addr = new char[strlen(stu._addr)+1];
strcpy(_addr, stu._addr);
return *this;
}
void print_info(){
cout << "ID: " << _id << endl;
cout << "Name: " << _name << endl;
cout << "Address: " << _addr << endl;
}
private:
int _id;
string _name;
char *_addr;
};
int main(){
Student stu1(1, "Alice", "123 Main Street");
Student stu2(2, "Bob", "456 Second Avenue");
stu1 = stu2;
stu1.print_info();
return 0;
}
```
这段代码实现了一个包含 ID、姓名和地址的学生类,并对赋值运算符进行了重载。在主函数中,我们创建了两个学生对象,并将 stu2 赋值给了 stu1。最后我们调用 print_info 函数输出 stu1 的信息。
输出结果如下:
```
ID: 2
Name: Bob
Address: 456 Second Avenue
```
希望这个答案对你有帮助!