声明:
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 在派生类定义之外丢失了其值?
谢谢!
base::base(int a){
cout << " in base constructor a = " << a << endl ;
a = a ;
}
此行更改构造函数参数的值 a
,而不是 base
的 a
的值。更好的将是
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 ;
}
在后一种情况下,您甚至可以写
base::base(int a): a(a) {
cout << " in base constructor a = " << a << endl ;
}
因为在初始化列表中没有歧义,尽管我仍然更喜欢显式并为构造函数参数和类成员使用不同的名称。