初始化数据类源代码:
<span style="font-size:14px;">#include<iostream>运行结果“
#include<string>
using namespace std;
class Student
{
public:
Student(int n,string nam){num=n;name=nam;}
void Student_cout();
protected:
int num;
string name;
};
void Student::Student_cout()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
}
class Student1:public Student
{
public:
Student1(int n,string nam,int n1,string nam1,int a,string ad):Student(n,nam),monitor(n1,nam1)
{
age=a;
addr=ad;
}
void Student1_cout();
void Sudent1_monitor_cout();
private:
Student monitor;
int age;
string addr;
};
void Student1::Student1_cout()
{
cout<<"This student is:"<<endl;
Student_cout();
cout<<"age:"<<age<<endl;
cout<<"address:"<<addr<<endl<<endl;
}
void Student1::Sudent1_monitor_cout()
{
cout<<endl<<"Class monitor is"<<endl;
monitor.Student_cout();
}
int main()
{
Student1 stud1(10010,"wang_li",10001,"Li_sun",19,"Beijing");
stud1.Student1_cout();
stud1.Sudent1_monitor_cout();
return 0;
}</span>
流插入运算符输入源代码:
#include<iostream>运行结果:
<span style="font-size:14px;">#include<string>
#include<cstring>
using namespace std;
class Student
{
public:
Student(){}
void Student_cin();
void Student_cout();
protected:
int num;
string name;
};
void Student::Student_cin()
{
cin>>num>>name;
}
void Student::Student_cout()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
}
class Student1:public Student
{
public:
Student1(){age=0;};
void Student1_cin();
void Student1_monitor_cin();
void Student1_cout();
void Sudent1_monitor_cout();
private:
Student monitor;
int age;
string addr;
};
void Student1::Student1_cout()
{
cout<<"This student is:"<<endl;
Student_cout();
cout<<"age:"<<age<<endl;
cout<<"address:"<<addr<<endl<<endl;
}
void Student1::Sudent1_monitor_cout()
{
cout<<endl<<"Class monitor is"<<endl;
monitor.Student_cout();
}
void Student1::Student1_cin()
{
cin>>num>>name>>age>>addr;
}
void Student1::Student1_monitor_cin()
{
monitor.Student_cin();
}
int main()
{
Student1 p1;
p1.Student1_cin();
p1.Student1_monitor_cin();
p1.Student1_cout();
p1.Sudent1_monitor_cout();
return 0;
}</span>
总结:
1.利用初始化数据时是一定要定义构造函数的,而且一定要用到的是有参数的构造函数,在使用流提取运算符输入数据时,类中是不需要构建构造函数的,但是在这里的这个源代码中是使用了构造函数,假使这里不使用构造函数的在下面的主函数中是不能够使用Student1定义一个变量的,这点现在还不知道是为什么;还有一个问题就是,假使在类中使用无参数的构造函数时(普通的赋值构造函数)系统会提示编译错误;
2.派生类构造函数的一般形式:
派生类构造函数名(总参数表):基类构造函数名(参数表)
{派生类中新增数据成员初始化语句}
3..有子对象派生类构造函数的一般形式:
派生类构造函数名(总参数表):基类构造函数名(参数表),子对象名(参数表)
{派生类中新增数据成员初始化语句}
4.基类构造函数中总参数表中的参数的顺序是任意,因为编译系统是根据相同的参数名来确立他们的传递关系的;
5.在执行派生类的构造函数时(有子对象),先调用基类构造函数,对基类数据成员初始化,然后调用子对象构造函数,对子对象数据成员初始化,在执行派生类构造函数本身,对派生类数据成员初始化;