#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();
}
C++类的构造函数与析构函数
最新推荐文章于 2024-05-22 00:03:53 发布