[英]c++ inheritance : confused with base member access from derived object
Declaration: 宣言:
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 ;
};
Definition : 定义:
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 ;
}
Call: 呼叫:
derived A(4,5) ;
cout << " a of A = " << A.getA() << "\n" ;
cout << " c of A = " << A.getC() << "\n" ;
Result : 结果:
in base constructor a = 4
a of A = 4205648
c of A = 9
Please can someone explain why I am getting this result instead of : 请有人能解释为什么我得到这个结果而不是:
a of A = 4
? ? Why does the value of base member a change ? 为什么基本成员的值发生变化? Based on what I've learned about inheritance in c++, when we create an object of derived class, this object will inherit all members and member functions of base class, why is it that the member a of object A
of class derived loses its value outside the derived class definition ? 根据我对c ++继承的了解,当我们创建派生类的对象时,该对象将继承基类的所有成员和成员函数,为什么派生类的对象A
的成员a失去其值在派生类定义之外?
Thanks ! 谢谢 !
base::base(int a){
cout << " in base constructor a = " << a << endl ;
a = a ;
}
This line changes the value of constructor parameter a
, not the value of a
of base
. 这行更改了构造函数参数a
的值,而不是base
的a
值。 Better will be 会更好
base::base(int _a){
cout << " in base constructor a = " << _a << endl ;
a = _a ;
}
And even better is to use constructor initialization list: 更好的是使用构造函数初始化列表:
base::base(int _a): a(_a) {
cout << " in base constructor a = " << a << endl ;
}
In the latter case you can even write 在后一种情况下,您甚至可以编写
base::base(int a): a(a) {
cout << " in base constructor a = " << a << endl ;
}
because in the initialization list there is no ambiguity, although I still prefer to be explicit and use different names for constructor parameters and class members. 因为在初始化列表中没有歧义,尽管我仍然更喜欢明确一些,并为构造函数参数和类成员使用不同的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.