【发布时间】:2021-11-02 08:03:00
【问题描述】:
我正在尝试编写一个重载的operator= 以将对象studentA 的内容复制分配给studentB。编译后,它只是崩溃并像往常一样“停止工作”。
#include <cstdlib>
#include <iostream>
using namespace std;
class STUDENT {
public:
string ID;
string name;
unsigned int birthyear;
STUDENT(string x, string y, unsigned int z) {
ID = x;
name = y;
birthyear = z;
};
STUDENT operator = (STUDENT const &obj) {
STUDENT *res;
*res = obj;
return *res;
}
void print() {
cout << ID << " " << name << " " << birthyear;
}
};
int main() {
STUDENT studentA("1951049", "Nguyen Vinh Hao", 2001);
STUDENT studentB("1951050", "Nguyen Van Hao", 1999);
studentB = studentA;
studentB.print();
return 0;
}
我认为指针*res 存在一些问题,但我真的不知道它们是什么。我希望你能帮助我。
【问题讨论】:
-
STUDENT *res;你认为这个指针指向哪里?而且你为什么还要在这里有一个指针? -
我们可以通过将一个对象的地址传递给另一个对象来复制成员的值吗?这是这里发生的事情吗?请问有人能解释一下吗。
标签: c++