lou*_*ice 0 c++ inheritance derived base
宣言:
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 ;
};
Run Code Online (Sandbox Code Playgroud)
定义:
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 ;
}
Run Code Online (Sandbox Code Playgroud)
呼叫:
derived A(4,5) ;
cout << " a of A = " << A.getA() << "\n" ;
cout << " c of A = " << A.getC() << "\n" ;
Run Code Online (Sandbox Code Playgroud)
结果:
in base constructor a = 4
a of A = 4205648
c of A = 9
Run Code Online (Sandbox Code Playgroud)
请有人解释为什么我得到这个结果而不是:
a of A = 4
Run Code Online (Sandbox Code Playgroud)
?为什么基础成员的价值会发生变化?根据我在c ++中学习的继承知识,当我们创建派生类的对象时,这个对象将继承基类的所有成员和成员函数,为什么A派生类的对象的成员a在外部失去其值派生类定义?
谢谢 !
base::base(int a){
cout << " in base constructor a = " << a << endl ;
a = a ;
}
Run Code Online (Sandbox Code Playgroud)
此行改变了构造函数的参数的值a,而不是价值a的base.会更好
base::base(int _a){
cout << " in base constructor a = " << _a << endl ;
a = _a ;
}
Run Code Online (Sandbox Code Playgroud)
甚至更好的是使用构造函数初始化列表:
base::base(int _a): a(_a) {
cout << " in base constructor a = " << a << endl ;
}
Run Code Online (Sandbox Code Playgroud)
在后一种情况下,你甚至可以写
base::base(int a): a(a) {
cout << " in base constructor a = " << a << endl ;
}
Run Code Online (Sandbox Code Playgroud)
因为在初始化列表中没有歧义,尽管我仍然更喜欢显式并为构造函数参数和类成员使用不同的名称.
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |