继承与派生
初识
类的继承是新类从已有的旧类那里获得的特性,从已有的类产生新类的过程称为类的派生。通过继承和派生,可以简化代码的编写,提高开发效率。已有的类称为基类或父类,派生出的新类称为派生类或子类。根据派生类所拥有的基类数目不同,可以分为单继承和多继承。
继承的访问控制
类的继承有私有继承、公有继承、保护继承3种。不同的继承方式,导致派生类对基类成员的访问能力有所不同。派生类对基类成员的访问能力如下:
基类成员 |
继承方式 |
派生类的访问 |
|
||
private |
|
不可访问 |
public |
private |
private |
protected |
|
private |
|
||
private |
|
不可访问 |
public |
public |
public |
protected |
|
protected |
|
||
private |
|
不可访问 |
public |
protected |
protected |
protected |
|
protected |
下面给出这三种继承的代码实现:
私有继承:
#include<iostream>
using namespace std;
class Base
{
private:
int a;
public:
void inita(int x)
{
a = x;
}
int geta()
{
return a;
}
};
class Derived:private Base
{
private:
int b;
public:
void initb(int x,int y)
{
b = y;
inita(x);
}
int getb()
{
return b+geta();
}
};
int main(void)
{
Derived obj1;
obj1.initb(12,3);
//obj1.inita(10); Error语句无法执行执行
//cout<<obj1.geta()<<endl; Error语句无法执行执行
cout<<obj1.getb()<<endl;
return 0;
}
/* 运行结果:15 */
公有继承:
#include<iostream>
using namespace std;
class Base
{
private:
int a;
public:
void inita(int x)
{
a = x;
}
int geta()
{
return a;
}
};
class Derived:public Base
{
private:
int b;
public:
void initb(int y)
{
b = y;
}
int getb()
{
return b+geta();
}
};
int main(void)
{
Derived obj1;
obj1.inita(12);
obj1.initb(3);
cout<<obj1.getb()<<endl;
return 0;
}
/* 运行结果:15 */
保护继承:
#include<iostream>
using namespace std;
class Base
{
private:
int a;
public:
int b;
protected:
int c;
void initab(int aa,int bb)
{
a = aa;
b = bb;
}
int geta()
{
return a;
}
};
class Derived:protected Base
{
private:
int c;
public:
void initabc(int aa, int bb, int cc)
{
initab(aa,bb);
c = cc;
}
int getc()
{
return c+b+geta();
}
};
int main(void)
{
Derived obj1;
//obj1.initab(12,13); Error,'void Base::initab(int,int)' is protected
obj1.initabc(12,13,5);
cout<<obj1.getc()<<endl;
return 0;
}
/* 运行结果:30 */
#include<iostream>
using namespace std;
class Rectangle
{
double len,wid;
public:
Rectangle(double a = 0,double b = 0)
{
len = a;
wid = b;
}
friend double area(Rectangle &rect);
};
double area(Rectangle &rect)//友元函数不是类的成员函数,所以在类体外定义时不必加“类名::”
{
return rect.len*rect.wid;
}
int main(void)
{
Rectangle obj1(4,5);
cout<<"The area is "<<area(obj1);
return 0;
}
/* 运行结果:20 */
#include<iostream>
#include<cstring>
using namespace std;
class boy; // 声明类boy
class girl
{
char *name;
int age;
public:
girl(char *n,int a) //定义构造函数
{
name = new char[strlen(n)+1];
strcpy(name,n);
age = a;
}
void prt(boy &b);// 开头需要先声明类boy,否则无法通过编译
};
class boy
{
char *name;
int age;
public:
boy(char *n,int a)
{
name = new char[strlen(n)+1];
strcpy(name,n);
age = a;
}
friend void girl::prt(boy &b);//定义友元成员
};
void girl::prt(boy &b)
{
cout<<"The girl's name is "<<name<<", her age is "<<age<<endl;
cout<<"The boy's name is "<<b.name<<", his age is "<<b.age<<endl;
}
int main(void)
{
girl gl("Marry",18);
boy by("John",18);
gl.prt(by);
return 0;
}
/*
运行结果:
The girl's name is Marry, her age is 18
The boy's name is John, his age is 18
*/