访问父类中的被覆盖成员、初始化父类构造函数

#include  < iostream.h >

class  A  //  父类A
{
public:
    A(
int x, int y)
        : a(x), b(y) 
{ cout<<"Address of object A: "<<this<<endl; }
//private:
    int a;
    
int b;
}
;

class  B: public  A  //  子类B
{
public:
    B(
int x, int y, int m, int n) 
        : A(x,y), a(m), b(n) 
{  cout<<"Address of object B: "<<this<<endl; }
//private:
    int a;
    
int b;
}
;

void  main()
{
    A a(
10,20);
    cout
<<a.a<<" "<<a.b<<endl;
    
    B b(1,2,3,4);
    cout<<sizeof(a)<<" "<<sizeof(b)<<endl;
    
    cout
<<b.a<<" "<<b.b<<endl;
    cout
<<b.A::a<<" "<<b.A::b<<endl; //access class A's member data overrided in class B
}

运行结果:
Address of object A: 0x0012FF78
10 20
Address of object A: 0x0012FF68
Address of object B: 0x0012FF68
8 16
3 4
1 2

测试2
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"


#include <iostream>


class Parent
{
public:
Parent()
{
std::cout << "Parent();" << std::endl;
}


Parent(int a, int b)
{
std::cout << "Parent(a=" << a << ",b=" << b << ");" << std::endl;
}
};


class Child1 : public Parent
{
public:
Child1()
: Parent(111, 222)
{
std::cout << "Child1() 1;" << std::endl;
}


Child1(int a, int b, int c, int d)
: Parent()
{
std::cout << "Child1(c=" << c << ",d=" << d << ");" << std::endl;
}
};


class Child2 : public Parent
{
public:
Child2()
: Parent()
{
std::cout << "Child2() 1;" << std::endl;
}


Child2(int a, int b, int c, int d)
: Parent(c, d)
{
std::cout << "Child2(c=" << c << ",d=" << d << ");" << std::endl;
}
};


class Child3 : public Parent
{
public:
Child3()
{
std::cout << "Child3() 1;" << std::endl;
}


Child3(int a, int b, int c, int d)
{
std::cout << "Child3(c=" << c << ",d=" << d << ");" << std::endl;
}
};


int _tmain(int argc, _TCHAR* argv[])
{
Child1 c11;
Child1 c12(1, 2, 3, 4);


Child2 c21;
Child2 c22(1, 2, 3, 4);


Child3 c31;
Child3 c32(1, 2, 3, 4);


return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值