第十二周课后实践:阅读程序

本文探讨了C++中类的继承与成员访问机制,包括不同类成员的访问方式和优先级,以及如何在派生类中调用基类的特定成员。通过示例代码演示了类B中的print函数在不同场景下的表现,展示了类继承和成员访问的基本概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)

代码:

 

#include <iostream>
using namespace std;
class A
{
public:
    A()
    {
        a=0;
    }
    A (int i)
    {
        a=i;
    }
    void print()
    {
        cout<<a<<"  ";
    }
private:
    int a;
};
class B: public A
{
public:
    B()
    {
        b=0;
    }
    B(int i, int j, int k): A(i),aa(j)
    {
        b=k;
    }
    //思考:这3处出现的print,有何区别
    void print()      //(1)
    {
        A::print();   //(2)
        aa.print();   //(3)
        cout<<b<<endl;
    }
private:
    int b;
    A aa;
};
int main()
{
    B test[2];
    test[0]=B(1,4,7);
    test[1]=B(2,5,8);
    for(int i=0; i<2; i++)
        test[i].print();
    return 0;
}


运行结果:

 

 

(2)

代码:

 

#include <iostream>
using namespace std;
class A
{
public:
    A(char *s)
    {
        cout<<s<<endl;
    }
};
class B:public A
{
public:
    B(char *s1, char *s2):A(s1)
    {
        cout<<s2<<endl;
    }
};
class C:public A
{
public:
    C(char *s1,char *s2):A(s1)
    {
        cout<<s2<<endl;
    }
};
class D:public B, C
{
public:
    D(char *s1,char *s2,char *s3,char *s4):B(s1,s2),C(s3,s4)
    {
        cout<<s4<<endl;
    }
};
int main()
{
    D d("class A","class B","class C","class D");
    return 0;
}


运行结果:

 

 

(3)

代码:

 

#include <iostream>
using namespace std;
class Base
{
public:
    Base(char i) { cout<<"Base constructor. --"<<i<<endl; }
};
class Derived1:virtual public Base
{
public:
    Derived1(char i,char j):Base(i)
    {
        cout<<"Derived1 constructor. --"<<j<<endl;
    }
};
class Derived2:virtual public Base
{
public:
    Derived2(char i,char j):Base(i)
    {
        cout<<"Derived2 constructor. --"<<j<<endl;
    }
};
class MyDerived:public Derived1,public Derived2
{
public:
    MyDerived(char i,char j,char k,char l,char m,char n,char x): Derived2(i,j), Derived1(k,l), Base(m), d(n)
    {
        cout<<"MyDerived constructor. --"<<x<<endl;
    }
private:
    Base d;
};
int main()
{
    MyDerived obj('A','B','C','D','E','F','G');
    return 0;
}


运行结果:

 

 

(4)

代码:

 

#include<iostream>
using namespace std;
class A
{
public:
   int n;
};
class B:public A {};   // class B:virtual public A{};
class C:public A {};   // class C:virtual public A{};
class D:public B,public C
{
public:
    int getn() {return B::n;}
};
int main()
{
   D d;
   d.B::n=10;
   d.C::n=20;
   cout<<d.getn()<<endl;
   return 0;
}


运行结果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值