如何调用父类 有参构造函数
2013-10-13 21:02
375 查看
[cpp] view
plaincopy
#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
A()
{
cout<<"A Constructed\n";
}
};
class B:A
{
public:
int c;
int d;
B()
{
cout<<"B Constructed\n";
}
};
int main()
{
B b;
return 1;
}
如上面代码所示,B类继承自A类,当生成B的实例b时,要先执行A的构造函数,然后执行B的构造函数。结果如下所示:
若B使用有参构造函数,如下面代码所示,仍然会调用A的无参构造函数。
[cpp] view
plaincopy
#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
A()
{
cout<<"A Constructed 1\n";
}
A(int a,int b)
{
this->a=a;
this->b=b;
cout<<"A Constructed 2\n";
}
};
class B:A
{
public:
int c;
int d;
B()
{
cout<<"B Constructed 1\n";
}
B(int c,int d)
{
this->c=c;
this->d=d;
cout<<"B Constructed 2\n";
}
};
int main()
{
B b(1,1);
return 1;
}
运行结果:
但是如何在构造函数中调用父类的有参构造函数呢?实现代码如下:
[cpp] view
plaincopy
#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
A()
{
cout<<"A Constructed 1\n";
}
A(int a,int b)
{
this->a=a;
this->b=b;
cout<<"A Constructed 2\n";
}
};
class B:A
{
public:
int c;
int d;
B()
{
cout<<"B Constructed 1\n";
}
B(int c,int d):A(100,200)
{
this->c=c;
this->d=d;
cout<<"B Constructed 2\n";
}
};
int main()
{
B b(1,1);
return 1;
}
运行结果:
可以看见确实执行了有参构造函数,但是,调用的父类有参构造函数的参数是在子类的构造函数实现时便确定的。
plaincopy
#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
A()
{
cout<<"A Constructed\n";
}
};
class B:A
{
public:
int c;
int d;
B()
{
cout<<"B Constructed\n";
}
};
int main()
{
B b;
return 1;
}
如上面代码所示,B类继承自A类,当生成B的实例b时,要先执行A的构造函数,然后执行B的构造函数。结果如下所示:
若B使用有参构造函数,如下面代码所示,仍然会调用A的无参构造函数。
[cpp] view
plaincopy
#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
A()
{
cout<<"A Constructed 1\n";
}
A(int a,int b)
{
this->a=a;
this->b=b;
cout<<"A Constructed 2\n";
}
};
class B:A
{
public:
int c;
int d;
B()
{
cout<<"B Constructed 1\n";
}
B(int c,int d)
{
this->c=c;
this->d=d;
cout<<"B Constructed 2\n";
}
};
int main()
{
B b(1,1);
return 1;
}
运行结果:
但是如何在构造函数中调用父类的有参构造函数呢?实现代码如下:
[cpp] view
plaincopy
#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
A()
{
cout<<"A Constructed 1\n";
}
A(int a,int b)
{
this->a=a;
this->b=b;
cout<<"A Constructed 2\n";
}
};
class B:A
{
public:
int c;
int d;
B()
{
cout<<"B Constructed 1\n";
}
B(int c,int d):A(100,200)
{
this->c=c;
this->d=d;
cout<<"B Constructed 2\n";
}
};
int main()
{
B b(1,1);
return 1;
}
运行结果:
可以看见确实执行了有参构造函数,但是,调用的父类有参构造函数的参数是在子类的构造函数实现时便确定的。
相关文章推荐
- C# 构造函数如何调用父类构造函数或其他构造函数
- 如何调用父类的构造函数
- 在C#的构造函数中,如何显式的先调用父类或者是自己的构造函数?
- C++子类如何调用父类构造函数
- QT学习笔记——如何调用父类的构造函数
- 如何调用父类的构造函数?
- Python 如何调用父类的构造函数
- 父类的构造函数中最好不要调用虚函数
- java继承之(隐式或显式)调用父类的构造函数
- C++类继承之子类调用父类的构造函数的实例详解
- 父类中调用子类构造函数实例化子类的实现
- 继承时显示调用父类的构造函数(浅)
- 如何让new操作符不分配内存,只调用构造函数
- 在子类中调用父类的带参数的构造函数
- 【转】 C++中如何在一个构造函数中调用另一个构造函数
- 子类如何调用父类方法
- 如何在Python中调用父类的同名方法
- 关于父类私有属性在子类构造函数中super调用的解释
- 在子类中调用父类的带参数的构造函数
- JS中子类中如何调用父类的同名方法(继承时候,父类的同名方法被覆盖了)