王鹿其 发表于 2023-11-10 13:39:24

为什么输出结果中不打印两行“无参构造函数”

#include<iostream>
using namespace std;
class person
{
public:
        person()
        {
                cout << "无参构造函数" << endl;
        }
        person(int age)
        {
                cout << "有参构造函数" << endl;
                m_age = age;
        }
        ~person()
        {
                cout << "析构函数" << endl;
        }
        person(const person& p)
        {
                m_age = p.m_age;
        }
        int m_age=0;
};
void test01()
{
        person p;
        p.m_age = 18;

        person p2(p);
        cout << "p2 age is" << p2.m_age << endl;

}
int main()
{
        test01();
        return 0;
}

isdkz 发表于 2023-11-10 13:39:32

程序中没有打印两行“无参构造函数”的原因是因为在程序中使用了拷贝构造函数,而没有调用无参构造函数。当创建p2对象时,使用了p对象的拷贝构造函数,而不是无参构造函数。因此,没有打印出“无参构造函数”的内容。

如果希望在创建p2对象时也调用无参构造函数,可以在拷贝构造函数中添加输出语句,或者在拷贝构造函数中调用无参构造函数来实现这一目的。
页: [1]
查看完整版本: 为什么输出结果中不打印两行“无参构造函数”