1. 程式人生 > 其它 >結構體建構函式(csdn上挑了個看得懂的搬的省得下次找叭到了)

結構體建構函式(csdn上挑了個看得懂的搬的省得下次找叭到了)

1.建構函式
(1)只要引數和型別不完全相同,就可以定義任意多個建構函式,以適應不同的初始化場合。
(2)建構函式不需要寫返回型別,且函式名與結構體名相同。
(3)結構體內會生成一個預設的建構函式(但不可見,如studentInfo(){}),如下,所以才可以直接定義studentInfo型別的變數而不進行初始化(因為它沒有讓使用者提供任何初始化引數)。
建構函式:

struct studentInfo{
int id;
char gender;
//預設生成的建構函式
studentInfo(int _id,char _gender){
//賦值
id=_id;
gender=_gender;
}
//只初始化gender
studentInfo(char _gender){
gender=_gender;
}
};

上面的int _id的id只是變數名(下面的版本也是,改成其它當然也行),另外建構函式也可以直接化簡成一行:

struct studentInfo{
int id;
char gender;
//預設生成的建構函式
studentInfo(int _id,char _gender): id(_id),gender(_gender){}
};
//這樣就可以在需要時直接對結構體變數進行賦值
studentInfostu=studentInfo(10086,'M');

小栗子:

#include<stdio.h>
#include<iostream>
using namespace std;
struct Point{
int x,y;
Point(){}
Point(int _x,int _y):x(_x),y(_y){}//用以提供x和y的初始化
}pt[10];
int main(){
int num=0;
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
pt[num++]=Point(i,j);
}
}
for(int i=0;i<num;i++){
printf("%d,%d\n",pt[i].x,pt[i].y);
}
system("pause");
}