C++基础(九)构造函数和析构函数

构造函数在对象被创建时调用

析构函数在对象被销毁时调用

class Person
{
	//构造函数
public:
	Person()
	{
		cout << "person 的构造函数被调用" << endl;
	}
	//析构函数
	~Person() {
		cout << "person 的析构函数被调用" << endl;
	}
};

前提声明 无参构造函数  有参构造函数  拷贝构造函数

class Person
{
	//构造函数
public:
	Person()
	{
		cout << "person 的构造函数被调用" << endl;
	}
	Person(int a)
	{
		age = a;
		cout << "person 的有参构造函数被调用" << endl;
	}
	Person(const Person const* p)
	{
		cout << "person 的拷贝构造函数被调用" << endl;
	}
	//析构函数
	~Person() {
		cout << "person 的析构函数被调用" << endl;
	}
private:
	int age;
};

构造函数调用的三种方式:

括号法    注意 :括号法不允许调用无参构造函数

Person p(10);
Person p2(p);

显示调用     注意 : 显示调用不允许使用拷贝构造    Person(p5);会报错

Person p3 = Person();
Person p4 = Person(20);
Person p5 = Person(p4);

隐式调用

Person p6 = 10;
Person p7 = p6;

猜你喜欢

转载自blog.csdn.net/we1less/article/details/108809256