public继承的赋值兼容规则
class base{};
class derived:public base{};
derived d;
b = d;
base&br = d;
base * pb = &d;
- 如果派生方式是 private 或protected,则上述三条不可行
直接基类和简介基类
//
// main.cpp
// 派生类的构造函数
//
// Created by MENGCHEN on 16/1/22.
// Copyright © 2016年 MENGCHEN. All rights reserved.
//
#include <iostream>
using namespace std;
class base {
int a,b;
public:
base(int numA,int numB);
void PrintInfo();
};
base::base(int numA,int numB){
a = numA;
b = numB;
}
void base::PrintInfo(){
cout<<a<<"\n"<<b<<endl;
}
class derive:public base {
int c;
public:
derive(int numA,int numB,int numC);
void PrintInfo();
};
derive::derive(int numA,int numB,int numC):base(numA,numB)
{
c = numC;
}
void derive::PrintInfo(){
base::PrintInfo();
cout<<c;
}
int main(int argc, const char * argv[]) {
// insert code here...
derive a(1,2,3);
a.PrintInfo();
return 0;
}
- 我们可以查看一下这段代码的输出来查看基类与子类的构建顺序与析构顺序
Baseconstructed//基类创建
deriveconstructed//子类创建
MoreDeriveconstructed//孙子创建
~MoreDeriveDesConstructed//孙子被析构
~deriveDesConstructed//子类被析构
BaseDesConstructed//基类被析构