c ++继承:与派生对象的基本成员访问混淆

时间:2015-10-13 10:32:45

标签: c++ inheritance base derived

声明:

class base{
public:
    base(){a=0;}
    base(int a);
    int getA();
    virtual ~base() ;
protected:
    int a ;
};
//
class derived : public base {
public:
    derived(){}
    derived(int a, int b) ;
    int getC() ;
    ~derived();
private:
    int c ;
};

定义:

base::base(int a){
    cout << "   in base constructor a = " << a << endl ;
    a = a ;
}
base::~base(){
    a = 0 ;
}
int base::getA(){
    return a ;
}
//
derived::derived(int a, int b)
:base(a)
{
    c = a+b ;
}
int derived::getC()
{
    return c ;
}
derived::~derived(){
    c = 0 ;
}

呼叫:

derived A(4,5) ;
cout << "   a of A = " << A.getA() << "\n" ;
cout << "   c of A = " << A.getC() << "\n" ;

结果:

in base constructor a = 4
a of A = 4205648
c of A = 9

请有人解释为什么我得到这个结果而不是:

a of A = 4 

?为什么基础成员的价值会发生变化?基于我在c ++中学习的继承知识,当我们创建派生类的对象时,这个对象将继承基类的所有成员和成员函数,为什么它是类的对象A的成员a derived在派生类定义之外丢失其值?

谢谢!

1 个答案:

答案 0 :(得分:5)

base::base(int a){
    cout << "   in base constructor a = " << a << endl ;
    a = a ;
}

此行更改构造函数参数a的值,而不是a的{​​{1}}的值。更好的将是

base

更好的是使用构造函数初始化列表:

base::base(int _a){
    cout << "   in base constructor a = " << _a << endl ;
    a = _a ;
}

在后一种情况下,你甚至可以写

base::base(int _a): a(_a) {
    cout << "   in base constructor a = " << a << endl ;
}

因为在初始化列表中没有歧义,尽管我仍然喜欢显式,并为构造函数参数和类成员使用不同的名称。