类的继承
类是C++面向对象编程的一个重要的组成部分,在之前也做过一些介绍。类的继承问题将带我们更好地、更深入地认识类这一概念。
子类继承父类的一些属性,这样就可以在不同的类型有相似的共同点时减小编程量,也因此在开发中十分重要。
C++语言中,一个派生类可以从一个基类里面派生,也可以从多个基类当中派生,从一个基类中派生的过程被称为单继承,从多个基类中派生的继承被称为多继承。
单继承的定义格式:
class Dev: public Base;
多继承的定义格式:
class C: public A, public B
当然,public和private的调用是要看情况的
继承当中的构造函数调用
由于子类是由父类派生出来的,因此在构造子类的过程当中,父类的构造函数也会被调用。比如以下程序
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class Animal {
public:
void eat()
{
cout << "animal eat" << endl;
}
void sleep()
{
cout << "animal sleep" << endl;
}
void breath()
{
cout << "animal breath" << endl;
}
Animal()
{
cout << "animal construct" << endl;
}
};
class Fish :public Animal
{
public:
Fish()
{
cout << "fish construct" << endl;
}
};
void main()
{
Animal cat;
cat.sleep();
Fish smallfish;
smallfish.breath();
}
运行的结果为
animal construct
animal sleep
animal construct
fish construct
fish breath
在一般调用子类的默认构造函数的时候,父类的构造函数都会被隐式调用
调用父类带参构造函数的例子:
#include<iostream>
#include<string>
using namespace std;
class Document {
public:
Document(string D_newname);
void getName();
string D_name;
};
Document::Document(string D_newName)
{
D_name = D_newName;
}
void Document::getName()
{
cout << "Document class's name is: " << D_name << endl;
}
class Book :public Document
{
public:
Book(string D_newName, string newName);
void getName();
void setPageCount(int newPageCount);
void getPageCount();
private:
int PageCount;
string Name;
};
Book::Book(string D_newName, string newName) :Document(D_newName)
//!!
//注意,这样的写法意思是将D_newName所代表的值传给Document
//!!
{
Name = newName;
}
void Book::getName()
{
cout << "book class's name is: " << Name << endl;
}
void Book::setPageCount(int newPageCount)
{
PageCount = newPageCount;
}
void Book::getPageCount()
{
cout << "The page of book is: " << PageCount << endl;
}
void main()
{
Book x("magezine", "function");
x.getName();
x.setPageCount(456);
x.getPageCount();
}
子类可以使用接口对父类元素进行修改,在此不举例
多继承的属性和单继承基本相似,在实例化多继承对象时,使用到的父类的构造函数都需要被调用才能正常执行
注:有时候在定义类内成员函数的时候会使用const关键字跟在函数声明之后,比如
void thwe() const;
这样,声明的函数里面的所有的数据都是不可以发生改动的
多继承中,如果两个或者多个基类当中有相同名字的变量,就要在变量前加上作用域运算符::以消除二义性,防止编译冲突。
派生类几乎可以继承基类的所有特征,除了构造函数、析构函数、用户定义的new运算符、用户定义的数值运算符以及友元关系