写出以下代码运行结果
#include <iostream>
using namespace std;
class A {
private:
int a;
public:
A()
{
a = 0;
}
A(int i)
{
a = i;
}
void Print() {
cout << a << ",";
}
};
class B :public A {
private:
int b1, b2;
public:
B()
{
b1 = 0; b2 = 0;
}
B(int i)
{
b1 = i; b2 = 0;
}
B(int i, int j, int k) :A(i), b1(j), b2(k)
{}
void Print()
{
A::Print();
cout << b1 << "," << b2 << endl;
}
};
int main()
{
B ob1, ob2(1), ob3(3, 6, 9);
ob1.Print();
ob2.Print();
ob3.Print();
return 0;
}
初次判断运行结果:0,0,0<<endl1,1,0<<endl3,6,9
正确结果:0,0,0<<endl0,1,0<<endl3,6,9
错误原因:B类对象ob2实参仅为一个则在创建ob2对象时应调用一个参数的构造函数即
B(int i)
{
b1 = i; b2 = 0;
}
并未为其base类A提供参数,故其base类调用构造函数时仍是无参构造函数为0
本题考点:1.继承关系中构造函数的调用规则:先基类后派生类,若多重继承则先基类后子类再派生类,按继承列表从左至右依次调用。
2.参数个数与构造函数调用规则:无参调用无参......