c++构造函数有关问题,初学者求大神指导哇哇。
c++构造函数问题,菜鸟求大神指导哇哇。。。。。
#include <iostream>
using namespace std;
class MyClass
{
int a;
public:
MyClass() { printf("ctor\n"); }
~MyClass() { printf("dtor\n"); }
};
void* operator new[](size_t size)
{
void* p = operator new(size);
printf("calling new[] with size=%d address=%p\n", size, p);
return p;
}
int main()
{
MyClass* mc = new MyClass[3];
printf("address of mc=%p\n", mc);
delete[] mc;
return 0;
}
为什么运行后结果是
而不是第一行输出构造函数功能,就是为什么不是先输出三行ctor,不是对象创建时,调用构造函数么??。。新手求大神指导
------解决思路----------------------
new MyClass[3];
要首先分配空间(调用 operator new[] ),然后再在分配的空间上执行构造函数,构造对象。
------解决思路----------------------
你只分配了内存,没有构造对象呀!
------解决思路----------------------
还有delete []也要自己写好,你只写了new[]呀?
#include <iostream>
using namespace std;
class MyClass
{
int a;
public:
MyClass() { printf("ctor\n"); }
~MyClass() { printf("dtor\n"); }
};
void* operator new[](size_t size)
{
void* p = operator new(size);
printf("calling new[] with size=%d address=%p\n", size, p);
return p;
}
int main()
{
MyClass* mc = new MyClass[3];
printf("address of mc=%p\n", mc);
delete[] mc;
return 0;
}
为什么运行后结果是
而不是第一行输出构造函数功能,就是为什么不是先输出三行ctor,不是对象创建时,调用构造函数么??。。新手求大神指导
------解决思路----------------------
new MyClass[3];
要首先分配空间(调用 operator new[] ),然后再在分配的空间上执行构造函数,构造对象。
------解决思路----------------------
你只分配了内存,没有构造对象呀!
------解决思路----------------------
还有delete []也要自己写好,你只写了new[]呀?