class 派生类名:继承方式 基类名
{
成员声明;
}
class Derived: public Base
{
public:
Derived ();
~Derived ();
};
公有派生类对象可以当作基类的对象使用(可以隐含转换),反之不行。
但是转换后,派生类只能使用从基类继承来的成员。
一般自己写新的构造函数,但c++11:使用using继承基类的构造函数,但是只能初始化从基类继承的成员。
先基类参数初始化,再派生类参数初始化
派生类名::派生类名(基类所需的形参,本类成员所需的形参):
基类名(参数表), 本类成员初始化列表
{
//其他初始化;
};
#include<iostream>
using namespace std;
class B {
public:
B();
B(int i);
~B();
void print() const;
private:
int b;
};
B::B() {
b=0;
cout << "B‘s default constructor called." << endl;
}
B::B(int i) {
b=i;
cout << "B‘s constructor called." << endl;
}
B::~B() {
cout << "B‘s destructor called." << endl;
}
void B::print() const {
cout << b << endl;
}
class C: public B {
public:
C();
C(int i, int j);
~C();
void print() const;
private:
int c;
};
C::C() {
c = 0;
cout << "C‘s default constructor called." << endl;
}
C::C(int i,int j): B(i), c(j){
cout << "C‘s constructor called." << endl;
}
派生类未定义复制构造函数的情况
派生类定义了复制构造函数的情况
先派生类参数析构,再基类参数析构
一般是同名隐藏规则,但是也可以通过作用域操作符访问
#include <iostream>
using namespace std;
class Base1 {
public:
int var;
void fun() { cout << "Member of Base1" << endl; }
};
class Base2 {
public:
int var;
void fun() { cout << "Member of Base2" << endl; }
};
class Derived: public Base1, public Base2 {
public:
int var;
void fun() { cout << "Member of Derived" << endl; }
};
int main() {
Derived d;
Derived *p = &d;
//访问Derived类成员
d.var = 1;
d.fun();
//访问Base1基类成员
d.Base1::var = 2;
d.Base1::fun();
//访问Base2基类成员
p->Base2::var = 3;
p->Base2::fun();
return 0;
}
原文:https://www.cnblogs.com/huanxifan/p/13378592.html