C++ 多重继承类操作练习 和 详解

(试题二) 多重继承类操作练习
对应图所示继承图,写出程序代码要求在应用程序中,建立C类队形,访问A类中的成员函数,并由set和get访问其数据成员。也访问B类中的成员函数onB。

一、C++ 多重继承类操作练习 和 详解

1. 习题

1.1 题目

(试题二) 多重继承类操作练习对应图所示继承图,写出程序代码要求在应用程序中,建立C类队形,访问A类中的成员函数,并由set和get访问其数据成员。也访问B类中的成员函数onB。

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.详解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JarvanStack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值