#include <string>
#include <iostream>
using namespace std;
class Base
{
public:
Base(){
cout<<"Base Construct.\n";
}
Base(const Base& b){
cout<<"Copy Construct of Base.\n";
}
virtual void Print(int i=0){
cout<<"Base\t"<<i<<endl;
}
};
class Derive:public Base
{
public:
Derive(){
cout<<"Derive Construct.\n";
}
void Print(int i=1){
cout<<"Derive\t"<<i<<endl;
}
};
void B1(Base b)
{
b.Print();
}
void B2(Base &b)
{
b.Print();
}
void B3(Base *b)
{
b->Print();
}
void D1(Derive d)
{
d.Print();
}
void D2(Derive &d)
{
d.Print();
}
void D3(Derive *d)
{
d->Print();
}
void drawLine()
{
cout<<"---------------\n";
}
int main()
{
Base b;
drawLine();
Derive d;
drawLine();
Base* pb = new Derive{};
drawLine();
B1(d);
drawLine();
B2(d);
drawLine();
B3(&d);
drawLine();
D1(d);
drawLine();
D2(d);
drawLine();
D3(&d);
}
上述代码的输出为
Base Construct.
---------------
Base Construct.
Derive Construct.
---------------
Base Construct.
Derive Construct.
---------------
Copy Construct of Base.
Base 0
---------------
Derive 0
---------------
Derive 0
---------------
Copy Construct of Base.
Derive 1
---------------
Derive 1
---------------
Derive 1
得出的结论如下:
- 子类的构造函数一定会先构造父类
- When an object as a parameter passed-by-value, it will call Copy Constructor
- When an object as a parameter passed-by-reference, it has none business with constructor. 按引用传参和其指针效果一样。
- 子类可以传给参数是父类的函数,会调用父类的复制构造函数。该参数实则已经是父类的对象,调用的虚函数也是父类虚函数表里的,参数的默认值也是父类的。
- 虚函数的默认值跟随虚函数表走的。也就是上述
Print(int i)
中i
的默认值取决于对象的虚函数表(是父类的还是子类的)。