C++类的构造函数与析构函数

#include <iostream>
//object initialization and cleanup
//constructor does the initialization work
//destructor does the cleanup work
//构造函数分为无参构造和有参构造
//构造函数也分为普通构造函数和拷贝构造函数
class Person
{
    int age;
public:
    Person()
    {
        std::cout<<"the Person's constructor no argument is called"<<std::endl;
    }
    Person(int a)
    {
        std::cout<<"the Person's constructor who has an argument is called"<<std::endl;
    }
    Person (const Person &p)
    {
        age = p.age;
        std::cout<<"the Person's copy constructor  is called"<<std::endl;
    }
    ~Person()
    {
        std::cout<<"the Person's destructor is called"<<std::endl;
    }
};
void test01(){ //普通的调用方法
    Person p1;
    Person p2(10);
    Person p3(p2);
};

void test02(){ //显式地调用构造函数
    Person p1;
    Person(10);//匿名对象,当前行结束后系统会自动回收
    //不要利用拷贝构造函数初始化匿名对象
    Person p2 = Person(10);
    Person p3 = Person(p2);

}void test03(){ //隐式调用构造函数
    Person p2 =10;//相当于Person p2 = Person(10)
    Person p3 =p2; //相当于 Person p3 = Person(p2)
}
int main() {
 test01();
 test02();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值