c++笔记
委托构造函数&复制构造函数&组合类构造函数&移动构造&派生类构造函数
构造函数无返回值,无return,无虚函数,可以重载,构造函数在对象创建时会自动调用
委托构造函数:
保持代码实现的一致性
复制构造函数:
用一个已经存在的对象初始化新对象
参数是本类对象的引用
复制构造函数调用的情况:
组合类构造函数:
c++11 移动构造
派生类构造函数
虚函数运行时绑定(多态)
class A {
public:
virtual void print() const {cout<<"this is A"<<endl;}
};
class B: public A {
public:
virtual void print() const {cout<<"this is B"<<endl;}
};
void test(A a)
{
a.print();
}
void test2(A* a)
{
a->print();
}
int main()
{
B b;
test(b);
test2(&b);
return 0;
}
结果是:
this is A
this is B
析构函数可以有虚函数
无参数表,无返回值
虚析构函数实现释放咨询的动态绑定,否则无法释放子类的资源
class BASE{
public:
//~BASE();
virtual ~BASE();
};
BASE:~BASE()
{
cout<<"BASE destructor"<<endl;
}
class Derived::public BASE{
public:
Derived();
//~Derived();
virtual ~Derived();
private:
int* p;
}
Derived::Derived()
{
p = new int(0);
}
Derived:~Derived()
{
cout<<"Derived destructor"<<endl;
delete p;
}
void fun(BASE* b){
delete b;
}
int main()
{
Base* b = new Derived();
fun(b);
return 0;
}
结果:BASE destructor
因为析构函数是非虚函数,编译时对象已确定。
结果:
Derived destructor
BASE destructor