class A {
public:
A() { cout<<"A's constructor"<<endl; }
virtual ~A() { cout<<"A's Destructor"<<endl; }
};
class B : public A {
public:
B() { cout<<"B's constructor"<<endl; }
virtual ~B() { cout<<"B's Destructor"<<endl; }
};
int main() {
B b;
return 0;
}
输出结果:
A’s constructor
B’s constructor
B’s Destructor
A’s Destructor
请按任意键继续…
构造顺序是先调用父类的构造函数,析构时先析构子类的,再析构父类的,理解成从外到内嵌套
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
#define IMIN numeric_limits<int>::min()
#define IMAX numeric_limits<int>::max()
#define FR(i,n) for(int i=0;i<n;i++)
#define CLC(x) memset(x,0,sizeof(x))
#define FILL(x,c) memset(x,c,sizeof(x))
using namespace std;
#include <iostream>
class A {
public:
A() { foo(); }
virtual ~A() { foo(); }
virtual void foo() { std::cout << "1"; }
void bar() { foo(); }
};
class B : public A {
public:
virtual void foo() { std::cout << "2"; }
};
int main() {
B b;
b.bar();
return 0;
}
输出结果:121
定义B b,首先调用父类构造函数,父类构造函数调用自己所在的
foo(),输出1,然后bar(),调用B的foo(),B的是默认析构函数,最后调用B的A的析构函数
不能利用函数参数const与否来重载,只能是返回类型不同或参数个数或参数类型不同
带你理解C++对象初始化的不同方式
#include<iostream>
using namespace std;
class MyClass
{
public:
int n;
public:
MyClass(int i = 0) : n(i) { cout <<"fir: "<< n<<endl; }
MyClass( MyClass &x) { n = ++(x.n); cout <<"sec:"<< n<<endl; }
MyClass &operator=( MyClass &x) { n = --x.n; cout <<"third:" <<n<<endl;
return *this;}
~MyClass() { cout << n; }
};
int main()
{
MyClass obj1(1), obj2(2);//直接初始化
MyClass obj3 = obj1;//复制初始化
MyClass obj4 ;//直接初始化
obj4 = obj2;//赋值运算符
return 0;
}
输出:
fir: 1
fir: 2
sec:2
fir: 0
third:1
1212请按任意键继续…
来看看全局对象,静态对象,局部对象的析构顺序
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
#define IMIN numeric_limits<int>::min()
#define IMAX numeric_limits<int>::max()
#define FR(i,n) for(int i=0;i<n;i++)
#define CLC(x) memset(x,0,sizeof(x))
#define FILL(x,c) memset(x,c,sizeof(x))
using namespace std;
#include <iostream>
class A {
public:
A() { cout<<"A's constructor"<<endl; }
virtual ~A() { cout<<"A's Destructor"<<endl; }
};
class B{
public:
B() { cout<<"B's constructor"<<endl; }
virtual ~B() { cout<<"B's Destructor"<<endl; }
};
class C{
public:
C() { cout<<"C's constructor"<<endl; }
virtual ~C() { cout<<"C's Destructor"<<endl; }
};
class D{
public:
D() { cout<<"D's constructor"<<endl; }
virtual ~D() { cout<<"D's Destructor"<<endl; }
};
class E{
public:
E() { cout<<"E's constructor"<<endl; }
virtual ~E() { cout<<"E's Destructor"<<endl; }
};
C c;
E e;
int main() {
A *pa = new A();
B b;
static D d;
static E e;
delete pa;
return 0;
}
C’s constructor
E’s constructor
A’s constructor
B’s constructor
D’s constructor
E’s constructor
A’s Destructor
B’s Destructor
E’s Destructor
D’s Destructor
E’s Destructor
C’s Destructor
请按任意键继续…
请按任意键继续…
构造函数的调用顺序是根据实际运行定义的先后
析构函数:
a.一旦delete就马上调用析构函数
b.局部对象的析构优先>static >global(同级之间按声明顺序逆序)