虚基类

</pre></p><span style="font-family: monospace; text-align: -webkit-center; white-space: pre; background-color: rgb(240, 240, 240);">多文件请看:http://blog.csdn.net/yjkwf/article/details/5347907  http://blog.csdn.net/yunyun1886358/article/details/5672574</span><p></p><pre name="code" class="cpp">#pragma once
/*多文件编译中去掉它会怎么样?让我给你两个有关多文件编译的链接吧,good luck.*/
#include<iostream>

#include<string>
using namespace std;
class Person{
private:
 string name;
 int year;
 char sex;
 string address;
 int phoneNumber;
public:
 Person(string n, int y, char s, string a, int p) :name(n), year(y), sex(s), address(a), phoneNumber(p){cout<<"test";} //Q2: 你觉得会输出几次"test"?
 void show(){
  cout << name
   << year
   << sex
   << address
   << phoneNumber;
 }
};
class Teacher :virtual public Person{//Q2:为什么用虚基类?
public:
 Teacher(string n, int y, char s, string a, int p, string t) :Person(n, y, s, a, p), title(t){} 
 void show(){
  cout << title;
 }
private:
 string title;
 
};
class Cadre : virtual public Person{//Q2:为什么用虚基类?
public:
 Cadre(string n, int y, char s, string a, int p, string po) :Person(n, y, s, a, p), post(po){}
 void show(){
  cout << post;
 }
private:
 string post;
};
class Teacher_Cader :public Teacher, public Cadre{
public:
 Teacher_Cader(string n, int y, char s, string a, int p, string t, string po, int w) :Person(n, y, s, a, p), Teacher(n, y, s, a, p, t), Cadre(n, y, s, a, p, po), wage(w){}
 void show(){
  Person::show();
  Teacher::show();
  Cadre::show();
  cout <<wage;
 }
protected:
 int wage;
};
int main(){
 Teacher_Cader tc("lili", 20, 'F', "7-311", 119, "teacher","cadre",5000); 
 tc.show();
}

A1:

:

A2:虚基类使得在继承间接共同基类时只保留一份成员,避免多份拷贝,占用较多的存储空间。

Q2.2:有关这一点,你可以数据成员属性由"private"改成"protected",然后在Teacher_Cader中"cout<<name",考虑下会不会存在二义性?

A2.2:不会,见A1


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值