预测输出?
#include
#include
#include
using namespace std;
class Test {
int x;
public:
void* operator new(size_t size);
void operator delete(void*);
Test(int i) {
x = i;
cout << "Constructor called \n";
}
~Test() { cout << "Destructor called \n"; }
};
void* Test::operator new(size_t size)
{
void *storage = malloc(size);
cout << "new called \n";
return storage;
}
void Test::operator delete(void *p )
{
cout<<"delete called \n";
free(p);
}
int main()
{
Test *m = new Test(5);
delete m;
return 0;
}
(一种)
new called
Constructor called
delete called
Destructor called
(B)
new called
Constructor called
Destructor called
delete called
(C)
Constructor called
new called
Destructor called
delete called
(D)
Constructor called
new called
delete called
Destructor called
答案: (B)
说明:考虑以下语句
Test *ptr = new Test;
上面的语句实际上发生了两件事–内存分配和对象构造;新关键字负责这两者。该过程的第一步是调用运算符 new来分配内存。另一步是实际调用构造函数。 new运算符仅允许我们更改内存分配方法,而对构造函数调用方法不做任何事情。关键字new负责调用构造函数,而不是运算符new 。这个问题的测验
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。