预见构造函数

构造函数的作用:对一个类的对象进行初始化。
构造函数的名字:与类名相同。
构造函数的特点:不具有任何类型,不返回任何值。在创建类的对象的时候系统会自动调用构造函数,如果用户没有定义构造函数,系统会自定义一个什么都不做的构造函数。只能执行一次,一般声明为public。

用构造函数实现数据成员的初始化。(不带类型的构造函数)

stu.h:

#ifndef STU_H
#define STU_H
#include <cstdio>
#include <iostream>
using namespace std;

class stu
{
	private:
		int data;
	public:
		stu(); //构造函数名与类名相同 
	    void display();
};

#endif

stu.cpp:

#include "stu.h"
#include <cstdio>
#include <iostream>
using namespace std;

stu::stu() //类名 + 域限定符 
{
	data = 100; //初始化 data = 10;
}

void stu::display() //成员函数 display 
{
	cout << data << endl;
}

main.cpp

#include "stu.h"
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
	stu stu1;
	stu1.display();
	
	return 0;
}

用构造函数实现数据成员的初始化。(带类型的构造函数)

a.h:

#ifndef A_H
#define A_H

class A
{
	private:
		int data;
	public:
		A(int pla); //带形参 
		void display();
	//protected:
};

#endif // A_H

a.cpp:

#include "a.h" // class's header file
#include <iostream>
using namespace std;

A::A(int pla)
{
	data = pla;
}

void A::display()
{
	cout << data << endl;
}

main.cpp:

#include "a.h" // class's header file
#include <iostream>
#include <cstdio>
#include <stdlib.h>
using namespace std;

int main()
{
	A a1(100); //初始化的时候后面加括号 
	a1.display();
	
	return 0;
}

用函数初始化列表对数据成员进行初始化

p.h:

#ifndef P_H
#define P_H
#include <iostream>
#include <string>
using namespace std;

class P
{
	private:
		int data;
		int norm;
		string num;
	public:
		P(int d,int n1,string n2):data(d),norm(n1),num(n2){}; //初始化列表
		void display();
};

#endif // P_H

p.cpp:

#include "p.h" // class's header file
#include <iostream>
using namespace std;

void P::display()
{
	cout << norm << " " << num << " " << data << endl;
	cout << "数计必胜" << endl;
}

main.cpp:

#include "p.h"
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
	P p1(90,610,"031502209"); //定义对象时把所需要赋的初值表示出来
	p1.display();
	
	return 0;
}

注:如果private内有数组的话,不能使用初始化列表,得在构造函数的函数体中用操作语句对其进行声明。

class P
{
    private:
        char s[105];
        int a;
    public:
        P(int pla,char s1[]):a(pla)
        {strcpy(s,s1);}
        void display();
};

原文地址:https://www.cnblogs.com/qq952693358/p/5524721.html