- malloc实现对象的构造函数
#include <iostream>
#include <cstdlib>
using namespace std;
class A{
public:
int num;
A(int x):num(x){}
~A(){}
void p(){
cout << num << endl;
}
};
int main()
{
// A* a = new A(1);
// a -> p();
void* mem = malloc(sizeof(A));
A* a = new(mem) A(1); //新放置
a -> p();
a -> ~a();
free(mem);
return 0;
}
- 析构函数可以显示调用吗?
#include <iostream>
using namespace std;
class B{
public:
B(){
cout << "B构造" << endl;
}
~B(){
cout << "B析构" << endl;
}
};
class A{
public:
int num;
B *nums;
A(int x):num(x){
nums = new B[3];
}
~A(){
delete[] nums;
cout << "A析构" << endl;
}
void p(){
cout << num << endl;
}
};
int main()
{
A a(1);
a.p();
a.~A();
return 0;
}
- 构造和析构的调用顺序:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <deque>
using namespace std;
//抽象类A
class A
{
public:
A()
{
cout<<"抽象类A的构造函数"<<endl;
}
//纯虚函数fun
virtual void fun1() = 0;
};
//抽象类B
class B
{
public:
B()
{
cout<<"抽象类B的构造函数"<<endl;
}
//纯虚函数fun
virtual void fun2() = 0;
};
//普通类C
class C
{
public:
C()
{
cout<<"类C的构造函数"<<endl;
}
};
//普通类D
class D
{
public:
D()
{
cout<<"类D的构造函数"<<endl;
}
};
//普通类C
class E
{
public:
E()
{
cout<<"类E的构造函数"<<endl;
}
};
//普通类D
class F
{
public:
F()
{
cout<<"类F的构造函数"<<endl;
}
};
//普通类D
class G
{
public:
G()
{
cout<<"类G的构造函数"<<endl;
}
};
//普通类D
class H
{
public:
H()
{
cout<<"类H的构造函数"<<endl;
}
};
//普通类D
class M
{
public:
M()
{
cout<<"类M的构造函数"<<endl;
}
};
class Test: public A,public B,virtual public C,virtual public D,public E,public F
{
public:
Test():B(),A(),D(),C(),F(),E()
{
cout<<"类Test的构造函数"<<endl;
}
void fun1()
{
}
void fun2()
{
}
private:
G g;
static H h;
static M m;
};
H Test::h;
M Test::m;
int main(int argc, char* argv[])
{
Test test;
return EXIT_SUCCESS;
}