首页 > 代码库 > 含参数的构造函数_将对象灵活的初始化

含参数的构造函数_将对象灵活的初始化

初始化过程和一般的变量相同

student::student(string na,string i)
{
    cout<<"it‘s creating"<<endl;
    name=na;id=i;
}
...............
string name="mark",id="651445";

    student s(name,id) ;    //将类初始化为可选择的值

  完整代码:

技术分享
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 class student
 5 {
 6 private:
 7     string name;
 8     string id;
 9 
10 public:
11     student(string na,string i);        //构造函数可重载  实现不同的初始化要求
12     ~student();
13     void output();
14 
15 };
16 student::student(string na,string i)
17 {
18     cout<<"it‘s creating"<<endl;
19     name=na;id=i;
20 }
21 student:: ~student(){cout<<"it‘s done"<<endl;}
22 
23 void student::output(){cout<<"name is "<<name<<" and id is "<<id<<endl;}
24 int main()
25 {
26     string name="mark",id="651445";
27 
28     student s(name,id) ;    //将类初始化为可选择的值
29     s.output();
30     return 0;
31 }
32 //it‘s creating
33 //name is mark and id is 651445
34 //it‘s done
View Code

 

含参数的构造函数_将对象灵活的初始化