第二周学习:构造函数constructor function

  1. 构造函数也是成员函数一种
  • 名字same as类名,无返回值,可有参数
  • 对象生成时构造函数被自动调用,对象生成后,构造函数就废了(构造函数的调用是在对象存在之前)
  • 阔以有多个构造函数
  1. why needs?
  • 就不用编写初始化函数了,也不会担心忘记调用初始化函数
  • 有的对象未初始化就使用,避免犯错。
  1. 使用
  • 必须有default constructor,如果你自己编写构造函数,则一定要编写默认构造函数(带满满的缺省参数or无参数)
  • 可通过初始化列表来初始化
  • 构造函数多态

构造函数在数组的使用:

#include<iostream>
using namespace std;
class Test{
    
    
	private:
		int x;
	public:
		Test():x(0){
    
    cout<<"Constructor 1 called\n";}
		Test(int n):x(n){
    
    cout<<"Constructor 2 called\n"; }
}; 

int main()
{
    
    
	Test a[2];
	Test b[2]{
    
    3,4};
	Test c[2]{
    
    3};
	Test* d = new Test[2];
	delete [] d;
	return 0;
}

结果:在这里插入图片描述
(补:Test* e[3]={new Test(3),new Test};,这个会调用构造函数2次,因为e是指针数组,指针并不会自动调用构造函数)

猜你喜欢

转载自blog.csdn.net/ZmJ6666/article/details/108550884