#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class a{
public:
a();
~a();
void s();
};
a::a(){
cout<<"构造函数"<<endl;
}
a::~a(){
cout<<"析构函数"<<endl;
}
void a::s(){
cout<<"ddd"<<endl;
}
int main(){
a* p1=(a*)malloc(sizeof(a));
p1->s();
free(p1);
return 0;
}
想问为什么我的程序无法调用构造函数和析构函数?
malloc函数只做内存申请操作,不做调用操作。
要想调用,建议不使用malloc
直接使用
a a2;
a2.s();
malloc 是从C语言继承过来的。参考 C++ Core Guidelines:
R.10: Avoid malloc() and free()
malloc() and free() do not support construction and destruction, and do not mix well with new and delete .