派生类的构造函数与基类的构造函数
来源:互联网 发布:如何成为一个网络作家 编辑:程序博客网 时间:2024/06/11 23:48
// 派生类的构造函数与基类的构造函数.cpp : Defines the entry point for the console application.
//如果基类有构造函数,则在生成派生类的对象时会先调用基类的构造函数,
//然后再调用派生类的构造函数。
#include "stdafx.h"
#include<iostream>
protected:
int num;
char name[10];
char sex;
public:
student(int n,char *na,char s)
{
num=n;
strcpy(name,na);
sex=s;
cout<<"基类的构造函数被调用"<<endl;
}//基类中带参数的构造函数。
void display()
{
cout<<num<<endl<<name<<endl<<sex<<endl;
}
};
class stud:public student
{
private:
int age;
public:
stud(int n,char *na,char s,int a):student(n,na,s)//注意这里派生类的构造函数的写法。
{
cout<<"派生类的构造函数被调用"<<endl;
age=a;
}
void display()
{
cout<<"派生类的display函数"<<endl<<num<<endl<<name<<endl<<sex<<endl<<age<<endl;
}
};
stud a(100,"chen",'M',23);
void main()
{
a.display();
system("pause");
}
/*运行结果
基类的构造函数被调用
派生类的构造函数被调用
派生类的display函数
100
chen
M
23
请按任意键继续. . .
*/
//如果基类有构造函数,则在生成派生类的对象时会先调用基类的构造函数,
//然后再调用派生类的构造函数。
#include "stdafx.h"
#include<iostream>
using namespace std;
class student
{protected:
int num;
char name[10];
char sex;
public:
student(int n,char *na,char s)
{
num=n;
strcpy(name,na);
sex=s;
cout<<"基类的构造函数被调用"<<endl;
}//基类中带参数的构造函数。
void display()
{
cout<<num<<endl<<name<<endl<<sex<<endl;
}
};
class stud:public student
{
private:
int age;
public:
stud(int n,char *na,char s,int a):student(n,na,s)//注意这里派生类的构造函数的写法。
{
cout<<"派生类的构造函数被调用"<<endl;
age=a;
}
void display()
{
cout<<"派生类的display函数"<<endl<<num<<endl<<name<<endl<<sex<<endl<<age<<endl;
}
};
stud a(100,"chen",'M',23);
void main()
{
a.display();
system("pause");
}
/*运行结果
基类的构造函数被调用
派生类的构造函数被调用
派生类的display函数
100
chen
M
23
请按任意键继续. . .
*/
0 0
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- 派生类的构造函数
- http://blog.csdn.net/mindfloating/article/details/51534289
- 学习java day01
- iOS - 小文件下载篇(下载完写入文件)
- Codeforces 364Div2
- Codeforces Round #364 (Div. 2) B
- 派生类的构造函数与基类的构造函数
- Service初学
- 欧拉函数
- Fiddler抓包工具
- hdu 3032 Nim or not Nim?(打表 sg函数)
- Java语言:if语句
- HDU5734 Acperience
- IOS动画开发总结
- js获取当前系统时间后台转化为long型