|
发表于 2023-11-9 21:15:31
|
显示全部楼层
问题出在person类的构造函数和拷贝构造函数中对m_age的赋值上。在person有参构造函数和拷贝构造函数中,使用了局部变量m_age来接收传入的age值或者p对象的m_age值。这样赋值只是在局部变量中进行,并没有对类的成员变量m_age进行赋值操作。所以在输出p2的年龄时,m_age的值还是默认的0,而不是传入的20。
解决方法是在构造函数和拷贝构造函数中,直接对类的成员变量m_age进行赋值操作,而不是使用局部变量。
修改后的代码如下:
- #include<iostream>
- using namespace std;
- class person
- {
- public:
- person()
- {
- cout << "person无参构造函数调用" << endl;
- }
- person(int age)
- {
- cout << "person有参构造函数的调用" << endl;
- m_age = age;
- }
- person(const person & p)
- {
- cout << "person拷贝构造的调用" << endl;
- m_age = p.m_age;
- }
- ~person()
- {
- cout << "person析构函数的调用" << endl;
- }
- int m_age;
- };
- void test01()
- {
- person p1(20);
- person p2(p1);
- cout << "p2的年龄为" << p2.m_age << endl;
- }
- int main()
- {
- test01();
- return 0;
- }
复制代码
这样修改后,p2的输出年龄就会正确地显示为20了。 |
|