(试题二) 多重继承类操作练习
对应图所示继承图,写出程序代码要求在应用程序中,建立C类队形,访问A类中的成员函数,并由set和get访问其数据成员。也访问B类中的成员函数onB。
一、C++ 多重继承类操作练习 和 详解
1. 习题
1.1 题目
1.2 答案
结构
(1) “A.cpp”
#include <iostream>
#include <stdio.h>
using namespace std;
/**
* @Author Jarvan
* @create 2020/9/14 11:18
* B extend A ,C extend b,
*/
class A {
public:
//this is constructor method.
A(void)
{
cout << "constructor of A" << endl;
}
string pA = "pA";
void methodA() {
cout << "class A:methodA() method executed!" << endl;
}
string getpA() {
return pA;
}
void setpA(string pA) {
pA = pA;
}
};
(2) “B.cpp”
#include <iostream>
using namespace std;
#include "A.cpp"
/**
* @Author Jarvan
* @create 2020/9/14 11:18
* B extend A ,C extend b,
*/
class B :public A {
public:
//this is constructor method.
B(void)
{
cout << "constructor of B" << endl;
}
void onB() {
cout << "class B:onB() method executed!" << endl;
}
};
(3) “C.cpp”
#include <iostream>
using namespace std;
#include "B.cpp"
/**
* @Author Jarvan
* @create 2020/9/14 11:18
* B extend A ,C extend b,
*/
class C :public B {
public:
//this is constructor method.
C(void)
{
cout << "constructor of A" << endl;
}
void sc() {
cout<<"class C : method sc() executed!"<<endl;
}
};
(4) “Main.cpp”
#include <iostream>
using namespace std;
#include "C.cpp"
int main()
{
C *c = new C();
//access the method of A
c->methodA();
//access the field of class A
cout<<c->getpA().c_str()<<endl;
//set the field of A
c->setpA("class C :I changed your field pA ,class A");
cout<<c->getpA().c_str()<<endl;
//access the method of B
c->onB();
return 0;
}
运行效果
2.详解
…