为什么Person* p3 = new Person[5](7)
这在以下代码中失败了?如何将operator new[]
用于参数化构造函数?如果想要使用new[]
调用参数化构造函数,该怎么办?
class Person
{
public:
int age;
Person(){}
Person(int age):age(age){}
void* operator new(size_t size) throw(bad_alloc)
{
cout<<"In overloaded new"<<endl;
return (::operator new(size));
}
void operator delete(void* ptr) throw()
{
cout<<"in overloaded delete"<<endl;
::operator delete(ptr);
}
void* operator new[](size_t size) throw(bad_alloc)
{
cout<<"operatoe new[]"<<endl;
return (::operator new[](size));
}
void operator delete[](void* ptr) throw()
{
cout<<"delete[]"<<endl;
::operator delete[](ptr);
}
};
int main()
{
Person *p1 = new Person(); //// This is fine
Person* p2 = new Person[5]; /// This is fine
Person* p3 = new Person[5](7) /////Want to invoke parametrized constructor..
delete p1;
return 0;
}
答案 0 :(得分:2)
new
表达式中的初始化程序必须与变量初始化的形式相同(参见[expr.new])。这意味着对于数组,只允许三种形式:
T * p1 = new T[N]; // default-initialization
T * p2 = new T[N](); // value-initialization
T * p3 = new T[N] { a, b, c }; // list-initialization
初始值设定项的含义与变量声明语句的含义相同。
答案 1 :(得分:1)
怎么样
Person* p = new Person[5]{7, 7, 7, 7, 7};