#include<stdio.h>
#include<iostream.h>
#include<string.h>
void main()
{
class stud
{private: //生命以下是私有的
int num;
char name[10];
char sex;
public: //声明以下是共有的
stud() //定义构造函数,此名字必需和类的名字相同
{
num=10010;
strcpy(name,"Wangli");
sex='F';
}
void display()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
};
};
stud stud1; //在定义对象stud1时,自动执行构造函数
stud1.display(); //从对象的外面来调用display函数
stud1.num;
}
C++面向对象之继承
所谓的继承就是在一个已存在的类基础上建立一个新的类。已存在的类称为基类(父类),新建的类称为(派生类或子类);
派生类或子类继承了父类所有数据成员和成员函数,并增加新的成员。
公用派生类:
#include<stdio.h>
#include<iostream.h>
#include<string.h>
void main()
{
class stud
{
private:
int num;char name[10];char sex;
public:
void display()
{cout<<"num"<<num<<endl;cout<<"name"<<name<<endl;cout<<"sex"<<sex<<endl;};
};
class student:public stud
{
private:
int age;char addr[30];
public:
void show()
{
// cout<<"num"<<num<<endl;
// cout<<"name"<<name<<endl;
// cout<<"sex"<<sex<<endl;
// cout<<"age"<<age<<endl;
void display();//上面四行是引用了基类的私有成员,错误。因此可以用void display代替,他是基类的公有成员。
cout<<"address"<<addr<<endl;
};
};
私有派生类:限制太多,一般不用
保护成员:由上面的代码可知,公用派生类不能访问基类的私有成员,如果想在派生类引用基类成员,可以将基类成员的私有改为保护成员protected;
#include<stdio.h>
#include<iostream.h>
#include<string.h>
void main()
{
class stud
{
protected:
int num;char name[10];char sex;
public:
void display()
{cout<<"num"<<num<<endl;cout<<"name"<<name<<endl;cout<<"sex"<<sex<<endl;};
};
class student:public stud
{
private:
int age;char addr[30];
public:
void show()
{
// cout<<"num"<<num<<endl;
// cout<<"name"<<name<<endl;
// cout<<"sex"<<sex<<endl;
// cout<<"age"<<age<<endl;
void display();//上面的四行代码也合法。
cout<<"address"<<addr<<endl;
};
};