C++多继承(多重继承)详解(二)命名冲突
2023-09-14 09:09:31 时间
命名冲突
当两个或多个基类中有同名的成员时,如果直接访问该成员,就会产生命名冲突,编译器不知道使用哪个基类的成员。这个时候需要在成员名字前面加上类名和域解析符::,以显式地指明到底使用哪个类的成员,消除二义性。
#include <iostream>
using namespace std;
//基类
class BaseA{
public:
BaseA(int a, int b);
~BaseA();
public:
void show();
protected:
int m_a;
int m_b;
};
BaseA::BaseA(int a, int b): m_a(a), m_b(b){
cout<<"BaseA constructor"<<endl;
}
BaseA::~BaseA(){
cout<<"BaseA destructor"<<endl;
}
void BaseA::show(){
cout<<"m_a = "<<m_a<<endl;
cout<<"m_b = "<<m_b<<endl;
}
//基类
class BaseB{
public:
BaseB(int c, int d);
~BaseB();
void show();
protected:
int m_c;
int m_d;
};
BaseB::BaseB(int c, int d): m_c(c), m_d(d){
cout<<"BaseB constructor"<<endl;
}
BaseB::~BaseB(){
cout<<"BaseB destructor"<<endl;
}
void BaseB::show(){
cout<<"m_c = "<<m_c<<endl;
cout<<"m_d = "<<m_d<<endl;
}
//派生类
class Derived:public BaseA,public BaseB{
public:
Derived(int a ,int b,int c,int d,int e);
~Derived();
public:
void display();
private:
int m_e;
};
Derived::Derived(int a, int b, int c, int d, int e):BaseA(a,b),BaseB(c,d),m_e(e){
cout<<"Derived constructor"<<endl;
}
Derived::~Derived(){
cout<<"Derived destructor"<<endl;
}
void Derived::display() {
BaseA::show(); //调用BaseA类的 show()函数
BaseB::show(); //调用BaseA类的 show()函数
cout<<"m_e = "<<m_e<<endl;
}
int main(){
Derived obj(1, 2, 3, 4, 5);
obj.display();
return 0;
}
请读者注意第 64、65 行代码,我们显式的指明了要调用哪个基类的 show() 函数。
相关文章
- C++虚继承
- Effective C++笔记(六):继承与面向对象设计
- c++中继承和java中继承的对比
- (C++)C++类继承中的构造函数和析构函数
- (C++)C++类继承中的构造函数和析构函数
- C/C++基础讲解(十七)之数据结构篇约瑟夫环与记录个人资料
- C语言/C++基础之跨年烟花程序代码(附源码)
- C语言/C++常见习题问答集锦(二十三)
- c++模板学习08之类模板与继承
- atitit.泛型编程总结最佳实践 vO99 java c++ c#.net php
- paip.提升性能--多核编程中的java .net php c++最佳实践 v2.0 cah
- paip.c++ qt __gxx_personality_sj0 __gxx_personality_v0问题的解决
- C++函数返回右值引用
- 编程之美之数独求解器的C++实现方法
- C++ primer札记10-继承
- C++虚继承时的构造函数
- c++ 输入与输出
- C++使用boost 1.75版本来读写JSON文件
- VC++调用gethostbyname实现域名解析(附源码)
- 【PAT 1151】 LCA in a Binary Tree C++版
- C++中继承与虚继承本质之优秀
- c++封装继承多态实例
- 【跟学C++】面向对象三大特征——继承(Study20)
- C++编程经验(12):C++11新特性
- 基于新版Opencv5.x(C++)+yolov6快速目标检测
- C++ 继承与多态详解2
- C/C++面试题分享