当我尝试编译以下内容时:
#include <iostream>
class Test
{
public:
void* operator new (size_t num);
void operator delete (void* test);
~Test();
private:
Test();
};
Test::Test()
{
std::cout << "Constructing Test" << std::endl;
}
Test::~Test()
{
std::cout << "Destroying Test" << std::endl;
}
void* Test::operator new (size_t num)
{
::new Test;
}
void Test::operator delete(void* test)
{
::delete(static_cast<Test*>(test));
}
int main()
{
Test* test = new Test;
delete test;
}
I get :
$ g++ -o test test.cpp
test.cpp: In function ‘int main()’:
test.cpp:14: error: ‘Test::Test()’ is private
test.cpp:36: error: within this context
如果new是一个成员函数,为什么它不能调用私有构造函数?
编辑: 我的想法是创建一个类,只能使用完全标准的语法在堆上实例化。我希望由于new是一个数据成员,它可以调用私有构造函数,但由于new不用于堆栈对象,因此您将无法在堆栈上创建对象。