标签:son cout 继承 子类 public 父类 class
*一个类继承多个类
语法:class 子类:继承方式 父类1 ,继承方式 父类2**
#include <iostream>
using namespace std;
class base1
{public:
base1()
{
a = 200;
}
int a;
};
class base2
{public:
base2()
{
a = 200;
}
int a;
};
class son :public base1, public base2
{
public:
son()
{
b = 600;
c = 700;
}
public:
int b;
int c;
};
void test()
{
son s;
cout << sizeof(son) << endl;
cout << s.base1::a << endl; //多继承容易产生成员同名的情况
//通过使用类名作用域可以区分调用哪一个基类的成员
cout << s.base2::a<< endl;
}
int main()
{
test();
system("pause");
return 0;
}
同名属性行为 函数访问
子类与父类出现同门属性行为时 子类对象可直接访问 访问父类的属性行为加上作用域
1当子类与父类拥有同名的成员函数,子类会隐藏父类中所有版本的同名成员函数,也就是说默认会调用子类的
2如果想访问父类中被隐藏的同名成员函数,需要加父类的作用域
#include <iostream>
using namespace std;
class base
{public:
base()
{ a = 200;
}
void fun()
{
cout << "鸡肋的函数" << endl;
}
void fun(int)
{
cout << "鸡肋的调用2" << endl;
}
int a;
};
class son:public base
{
public:
son()
{
a = 600;
}
void fun()
{
cout << "子类的函数" << endl;
}
public:
int a;
};
void test()
{
son s;
cout << sizeof(son) << endl;
cout <<s.a<< endl;
cout << s.base::a << endl;
}
int main()
{
//test();
son s1;
s1.fun();//不加鸡肋的域 默认都是子类的调用
s1.base::fun();
s1.base::fun(10);//只要是同名 就得加作用域才能调用
system("pause");
return 0;
}
同名的静态属性 静态函数的调用
和上述同名属性行为的调用方法大体一致。
#include <iostream>
using namespace std;
class base
{public:
static void fun()
{
cout << "鸡肋的静态函数" << endl;
}
static void fun(int)
{
cout << "鸡肋的静态调用2" << endl;
}
public:
static int a;
};
int base::a = 100; //类内定义 类外访问
class son:public base
{
public:
static void fun()
{
cout << "子类的静态函数" << endl;
}
public:
static int a;
};
int son::a = 600;
void test()
{//通过对象调用
son s;
cout << s.a << endl; //不加作用域 调用的还是子函数的属性 行为
cout << s.base::a << endl;
//通过类名调用
cout << son::a << endl;
cout << son::base::a << endl;
}
//同名静态函数调用
void test01()
{
cout << "对象调用" << endl;
cout << "*********************************************************" << endl;
son s1;
s1.fun();
s1.base::fun();
s1.base::fun(200);
cout << "通过类来调用" << endl;
cout << "****************************************************" << endl;
son::fun();
son::base::fun();
son::base::fun(100);//son::fun(100)调用不了 同名就得加作用域
}
int main()
{
test();
test01();
system("pause");
return 0;
}
菱形继承
继承前加virtual关键字后,变为虚继承
此时公共的父类Animal称为虚基类
#include <iostream>
#include <string>
using namespace std;
class animal
{
public:
int age;
};
class dog:virtual public animal
{};
class cat:virtual public animal{};
class cdg:public dog,public cat
{};
//访问
void test() {
cdg tt;
tt.cat::age = 10;
tt.dog::age = 50;
tt.age = 60; //如果不加virtual 那么识别不出来这个age
cout << tt.cat::age << endl;
cout << tt.dog::age << endl;
cout << tt.age << endl;//加入virtual 之后共用一个age
}
标签:son,cout,继承,子类,public,父类,class 来源: https://blog.csdn.net/weixin_51264282/article/details/115656771
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。