|
发表于 2023-11-10 16:25:39
|
显示全部楼层
这个C++代码中的主要问题是你没有正确实现拷贝构造函数。对于类 phone 和 person ,你的拷贝构造函数没有正确复制对象的数据,这可能会导致问题。
修改后的代码如下:
- #include<iostream>
- #include<string>
- using namespace std;
- class phone
- {
- public:
- phone(string pname)
- {
- cout << "phone的函数调用" << endl;
- p_name = pname;
- }
- ~phone()
- {
- cout << "phone的析构函数调用" << endl;
- }
- phone(const phone&p)
- {
- cout << "phone的拷贝函数调用" << endl;
- p_name = p.p_name; // 这里需要复制对象的数据
- }
- string p_name;
- };
- class person
- {
- public:
- person(string name, string phonename) :m_phone(phonename)
- {
- cout << "person的构造函数调用" << endl;
- m_name = name;
- }
- ~person()
- {
- cout << "person的析构函数调用" << endl;
- }
- person(const person& p) : m_phone(p.m_phone) // 需要使用初始化列表来初始化m_phone
- {
- cout << "person的拷贝函数调用" << endl;
- m_name = p.m_name; // 这里需要复制对象的数据
- }
- string m_name;
- phone m_phone;
- };
- void test01()
- {
- person p("张三","苹果max");
- cout << p.m_name << "拿着" << p.m_phone.p_name << endl;
- }
- int main()
- {
- test01();
- return 0;
- }
复制代码
这个修订的版本应该能够正确地复制 phone 和 person 对象。 |
|