

#include <iostream>
#include <string>
using namespace std;
//多继承
class Base1 {
public:
Base1() {
a = 100;
}
int a;
};
class Base2 {
public:
Base2() {
b = 200;
}
int b;
};
//子类 集成Base1和Base2
//语法 class 子类 :public 父类1,public 父类2...
class Son : public Base1, public Base2 {
public:
Son() {
c = 300;
}
int c;
};
void test() {
Son s;
cout << sizeof(s) << endl;
}
int main() {
test();
return 0;
}
12
#include <iostream>
#include <string>
using namespace std;
//多继承
class Base1 {
public:
Base1() {
a = 100;
}
int a;
};
class Base2 {
public:
Base2() {
a = 200;
b = 200;
}
int a;
int b;
};
//子类 集成Base1和Base2
//语法 class 子类 :public 父类1,public 父类2...
class Son : public Base1, public Base2 {
public:
Son() {
c = 300;
}
int c;
};
void test() {
Son s;
cout << sizeof(s) << endl;
//当父类出现同名成员,需要加作用域区分
cout << "base1 a=" << s.Base1::a << endl;
cout << "base2 a=" << s.Base2::a << endl;
}
int main() {
test();
return 0;
}
C++多继承示例
本文介绍了C++中多继承的基本概念及其实现方式,并通过具体代码示例展示了如何定义和使用多继承类。特别关注了当基类存在同名成员变量时如何正确访问的问题。
808

被折叠的 条评论
为什么被折叠?



