【发布时间】:2015-03-19 17:16:30
【问题描述】:
当我们在 c++ 中对类使用 malloc/free 时,不会创建对象。那么为什么这段代码有效呢? 如果一个对象没有被创建,那么它一定不能给出下面提到的输出。
class Test
{
public:
Test()
{
cout << "Test : ctor\r\n";
}
~Test()
{
cout << "Test : dtor\r\n";
}
void Hello()
{
cout << "Test : Hello World\r\n";
}
};
int main()
{
cout << "2\n";
Test* t2 = (Test*) malloc(sizeof Test);
t2->Hello();
free(t2);
return 0;
}
OUTPUT:
Hello World
【问题讨论】:
-
你的代码不起作用,因为你的构造函数和析构函数中的 cout 语句没有被执行。
-
为什么在 C++ 代码中使用
malloc? (还有演员表!)
标签: c++